POSIX pthread_join在数千个线程之后挂起

时间:2018-03-27 11:17:01

标签: c pthreads posix pthread-join

我是POSIX的新手,我无法找到解决此特定问题的方法。

在循环内部创建具有大量迭代次数(> 100000)的pthreads是否存在任何已知问题?

似乎每次执行时,它都会随机挂起pthread_join

  • 我已经使用valgrind测试了内存泄漏和线程堆栈的使用情况。
  • 如果我在程序挂起时中断gdb,它会将问题追踪到pthread_join

这是示例代码重新创建我的问题。

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>

    void* task(void* args);
    int main(int argc, char **argv)
    {
        int num_threads = 4;
        int m = 100000;
        int i;
        for(i = 0; i < m; i++)
        {
            fprintf(stdout, "i:%d\n",i);
            //parallel region starts
                pthread_t threads[num_threads];
                int t,rc;

                for(t = 0; t < num_threads; t++)
                {
                    rc = pthread_create(&threads[t],NULL,task,NULL);
                    if(rc){
                        fprintf(stderr,"ERROR; return code from pthread_create() is %d\n", rc);
                        exit(-1);
                    }
                }
                for(t = 0; t < num_threads; t++)
                {
                    rc = pthread_join(threads[t],NULL);
                    if(rc){
                    fprintf(stderr,"ERROR; return code from pthread_join() is %d\n", rc);
                        exit(-1);
                    }
                }
            //parallel region ends
        }
        pthread_exit(NULL);
    }

    //thread task
    void* task(void* args)
    {
        pthread_exit(NULL);
    }

1 个答案:

答案 0 :(得分:1)

在Ubuntu机器i7-4600U CPU @ 2.10GHz上验证您的代码 我没有看到您的代码有任何问题,只是为了验证我编译并在我的本地计算机上运行您的代码似乎工作正常。

我得到了预期的输出:

i:999,j:999

所以我假设您正在尝试的问题与您的环境有关。你正在使用什么CPU操作系统和GCC?

相关问题