简体   繁体   English

线程不终止他们的工作

[英]Thread don't terminate their job

I am writing a concurrent C program where I want to wait for all threads to finish in the main() . 我正在编写一个并发的C程序,我想在其中等待main()中的所有线程完成。

Based on this solution , I wrote the following code in 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 %d\n", t_iter);
    int result = pthread_join(cid[t_iter], NULL);
}

printf("Done mapping.\n");

The function passed into threads is defined as: 传递给线程的函数定义为:

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

The threads are all successfully created and executed, but the join loop will never finish if num_mappers >= 2. 所有线程均已成功创建和执行,但是如果num_mappers > = 2,则连接循环将永远不会结束。

You return without unlocking the mutex: 您返回时未解锁互斥锁:

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

So only one thread ever returns and ends - the first one, but since it never unlocks the mutex, the other threads remain blocked. 因此,只有一个线程返回并结束-第一个线程,但是由于它从未解锁互斥锁,因此其他线程仍然处于阻塞状态。

You need something more like 您需要更多类似的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM