【发布时间】:2018-04-17 14:17:59
【问题描述】:
我正在编写一个并发 C 程序,我想在其中等待 main() 中的所有线程完成。
基于this solution,我在main()中写了如下代码:
// Create threads
pthread_t cid[num_mappers];
int t_iter;
for (t_iter = 0; t_iter < num_mappers; t_iter++){
pthread_create(&(cid[t_iter]), NULL, &map_consumer, NULL);
}
// Wait for all threads to finish
for (t_iter = 0; t_iter < num_mappers; t_iter++){
printf("Joining %d\n", t_iter);
int result = pthread_join(cid[t_iter], NULL);
}
printf("Done mapping.\n");
传入线程的函数定义为:
// Consumer function for mapping phase
void *map_consumer(void *arg){
while (1){
pthread_mutex_lock(&g_lock);
if (g_cur >= g_numfull){
// No works to do, just quit
return NULL;
}
// Get the file name
char *filename = g_job_queue[g_cur];
g_cur++;
pthread_mutex_unlock(&g_lock);
// Do the mapping
printf("%s\n", filename);
g_map(filename);
}
}
线程全部成功创建并执行,但如果num_mappers >= 2,则连接循环永远不会结束。
【问题讨论】:
-
当
g_cur大到可以退出时,map_consumer会发生什么?线程是否保留其pthread_mutex_lock? -
@grorel 哦,我明白了!我必须在返回之前
unlock,否则所有其他线程都只是在等待获得锁。谢谢!
标签: c multithreading pthreads