我正在编写一个并发 C 程序,我想等待所有线程在 main()
中完成。
基于这个解决方案,我在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 %dn", 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("%sn", filename);
g_map(filename);
}
}
线程都已成功创建和执行,但如果 num_mappers
>= 2,则连接循环将永远不会完成。
返回时不解锁互斥锁:
pthread_mutex_lock(&g_lock);
if (g_cur >= g_numfull){
// No works to do, just quit
return NULL; <-- mutex is still locked here
}
// Get the file name
char *filename = g_job_queue[g_cur];
g_cur++;
pthread_mutex_unlock(&g_lock);
因此,只有一个线程返回并结束 - 第一个线程,但由于它永远不会解锁互斥锁,因此其他线程仍然被阻塞。
你需要更多类似的东西
pthread_mutex_lock(&g_lock);
if (g_cur >= g_numfull){
// No works to do, just quit
pthread_mutex_unlock(&g_lock);
return NULL;
}
// Get the file name
char *filename = g_job_queue[g_cur];
g_cur++;
pthread_mutex_unlock(&g_lock);