线程不会终止他们的工作

时间:2018-04-17 14:18:00

标签: c multithreading pthreads

我正在编写并发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&gt; = 2,则连接循环将永远不会完成。

1 个答案:

答案 0 :(得分:2)

您在不解锁互斥锁的情况下返回:

List<String>

因此只有一个线程会返回并结束 - 第一个,但由于它永远不会解锁互斥锁,所以其他线程仍然被阻塞。

你需要更像

的东西
List<MyNonGenericClass>