简体   繁体   English

pthread 在 C 中崩溃

[英]pthread getting crashed in C

I am trying multithreading in my C project, using pthread.我正在使用 pthread 在我的 C 项目中尝试多线程。 I was playing with this code but it is getting crashed and don't know why.我在玩这段代码,但它崩溃了,不知道为什么。

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

int g = 0;

void *myThreadFun(void *vargp)
{
    int *myid = (int *)vargp;
    static int s = 0;

    for(int n=0;n<1000;n++)
    {
        printf("%d\t%d\n", *myid, n); // .... line 13
    }

    printf("Thread number: %d, Static: %d, Global: %d\n", *myid, s, g);
    ++s; ++g;
}

void function()
{
    int noa=10;
    pthread_t threads[noa];
    int rc;

    for(int c=0;c<noa;c++)
    {
        rc = pthread_create(&threads[c], NULL, myThreadFun, (void *)&threads[c]);
        if (rc) {
            printf("Error:unable to create thread, %d\n", rc);
            exit(-1);
        }
        //pthread_join(threads[c], NULL); // .... line 33
    }
    pthread_exit(NULL);
}

int main()
{
    function();
}

1. If I delete line 13: printf("%d\t%d\n", *myid, n); 1.如果我删除第13行: printf("%d\t%d\n", *myid, n); it works properly.它工作正常。

I think every thread function have their own variable n and after some cycles they can access their own variable.我认为每个线程 function 都有自己的变量 n ,经过一些周期后,他们可以访问自己的变量。 So, why it crashed???那么,为什么它崩溃了???

2. If I use line 33: pthread_join(threads[c], NULL); 2.如果我使用第 33 行: pthread_join(threads[c], NULL); ,then it works but the thread works sequentially which I think perform slower. ,然后它可以工作,但线程按顺序工作,我认为执行速度较慢。

Can someone suggest me a better approach to use faster multithreading.有人可以建议我更好的方法来使用更快的多线程。

When your main() exits, the other threads are still running and using live variables (*thr == &threads[c]) from main()s stack frame.当您的 main() 退出时,其他线程仍在运行并使用 main() 堆栈帧中的实时变量 (*thr == &threads[c])。 The operation of those references is highly dependent upon your runtime and arbitrary timing.这些引用的操作高度依赖于您的运行时间和任意时间。 So first up:所以首先:

 for(int c=0;c<noa;c++)
    {
        rc = pthread_create(&threads[c], NULL, myThreadFun, (void *)&threads[c]);
        if (rc) {
            printf("Error:unable to create thread, %d\n", rc);
            exit(1);
        }
    }
 for(int c=0;c<noa;c++)
        {
            rc = pthread_join(threads[c], NULL);
            if (rc) {
                printf("Error:unable to join thread %d, %d\n", c, rc);
                exit(1);
            }
        }

Now your threads all run in parallel, and only when they have all completed, will main exit, thus the thread array will remain live until all references to it are dead.现在您的线程全部并行运行,只有当它们全部完成时,主程序才会退出,因此线程数组将保持活动状态,直到所有对它的引用都死了。

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

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