如何产生n个线程?

我正在尝试编写一个multithreading程序,基于命令行输入的线程数,所以我不能硬编码预先声明的线程。 这是一种有效的方法吗?

int threads = 5; // (dynamic, not hard-coded) int i = 0; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { pthread_t foobar; thread[i] = foobar; // will this cause a conflict? } for (i = 0; i < threads; i++) { int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } } 

这是我在下面建议的修改结果。 似乎工作得很好。

 int threads = 5; int i; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } // pthread_join(thread[i], NULL); // don't actually want this here :) } sleep(1); // main() will probably finish before your threads do, free(thread); // so we'll sleep for illustrative purposes 

第一个周期是什么? 它是否将数组元素设置为未初始化的值?

所以我认为这就是你所需要的:

 int threads = 5, i = 0, ret = -1; pthread_t * thread = malloc(sizeof(pthread_t)*threads); for (i = 0; i < threads; i++) { ret = pthread_create(&thread[i], NULL, &foobar_function, NULL); if(ret != 0) { printf ("Create pthread error!\n"); exit (1); } } 

它产生线程线程,在每个线程中启动foob​​ar_function 。 你有(如果一切顺利):)他们在线程数组中的ID。 因此,例如,您可以通过调用pthread_cancel(thread[1])等来取消第二个线程。

第一个for循环是无效的C,我不确定你想要它做什么。 除了foobar_function上的不正确的foobar_function外,只需将其删除,其余代码看起来就foobar_function 。 演职员应该是:

 (void *(*)(void *))foobar_function 

但除非类型已经是这个,或者非常接近,否则您的程序可能具有未定义的行为。 最好修复函数签名,这样就不需要强制转换。

如果您正在尝试编写multithreading程序,但不了解如何分配动态大小的数据结构,那么您可能会做错事。

跑步之前学会走路。

考虑使用更简单的语言,并避免使用(显式)线程。

线程很难正确使用; 动态大小的数组很容易实现(在C中甚至相当容易)