Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

multithreading - pthread getting crashed in C

I am trying multithreading in my C project, using pthread. 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%d
", *myid, n); // .... line 13
    }

    printf("Thread number: %d, Static: %d, Global: %d
", *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
", rc);
            exit(-1);
        }
        //pthread_join(threads[c], NULL); // .... line 33
    }
    pthread_exit(NULL);
}

int main()
{
    function();
}

1. If I delete line 13: printf("%d%d ", *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. So, why it crashed???

2. If I use line 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 .

question from:https://stackoverflow.com/questions/65873601/pthread-getting-crashed-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When your main() exits, the other threads are still running and using live variables (*thr == &threads[c]) from main()s stack frame. 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
", 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
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...