【问题标题】:Thread don't terminate their job线程不会终止他们的工作
【发布时间】: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


【解决方案1】:

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

    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);

【讨论】:

  • 在这些情况下,在 C 中使用某种 RAII 或 try/finally 会很好,但我想这就是 C++ 存在的原因。
  • @Groo:我也是这么想的,RAII 规则! ;) 我已经多次成功地将 C++ 与纯 pthreads 结合使用,以防 pthreads 之上的薄 std::thread 层隐藏了我需要的一些更奇特的 pthreads 设置/配置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 2014-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多