我正在尝试编写一个多线程程序,基于命令行输入的线程数,所以我不能硬编码预先声明的线程.这是一种有效的方法吗?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
以下是我在下面建议的修改结果.似乎工作得很好.
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
Run Code Online (Sandbox Code Playgroud)
小智 7
第一个周期是什么?它是否将数组元素设置为未初始化的值?
所以我认为这就是你需要的:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
它产生线程线程,在每个线程中启动foobar_function.你有(如果一切顺利):)他们在线程数组中的ID .例如,您可以通过调用pthread_cancel(thread[1])
等取消第二个线程.