【发布时间】:2011-02-10 23:56:09
【问题描述】:
我正在尝试编写一个多线程程序,线程数基于命令行输入,因此我无法对预先声明的线程进行硬编码。这是一种有效的方法吗?
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 = argv[3]位中的字符串。您必须使用atoi或 sscanf -
好吧,
pthread_join()是它所在的位置,您应该创建线程,然后等待它完成,然后再生成下一个线程。所以实际上你在这里是准单线程的:) -
当我在没有连接的情况下运行它时,它认为它不会执行函数......(我让 foobar_function 只是打印出一行快速的文本)。我错过了一步吗? .. EDIT 实际上,我猜它正在工作.. 有时它会打印出文本,但大多数时候它不会:P.