• Uncategorized

About c : Multithreading-simple-program-Segment-fault-core-dumped

Question Detail

I am trying to create a program which calculates prime numbers from 1 to 1000. I believe the code is having trouble either creating or joining the pthreads. I keep getting a core dump error. My main concern is in the second for loop where I am joining the pthreads. Is this the correct way to check if a thread has ended?

I am using gcc –std=c99 -Wall -Werror -pthread primes.c -o primes in the terminal.

    while (test_val <= FINAL){
        //loop to check if thread is finished
        for(int i = 0; i < THREADS; i++){
            if(tid[i] == 0){
                pthread_create(&tid[i], NULL, testprime, NULL);

            }   
        }
        //wait for thread to end
        for(int i = 0; i < THREADS; i++){
            pthread_join(tid[i], NULL);

This is the error:
Segmentation fault (core dumped)

Question Answer

Here:

for(int l = 0; ti < MAX_THREADS; ti++){
    if(tid[l] == 0){
        pthread_create(&tid[l], NULL, testprime, NULL);
        tid[l] = 1;
    }   
}

First argument of pthread_create is an output thread handle. On the next line, you’re setting this value to 1 (probably to mark it as used).

When performing pthread_join on those invalid handles, you invoke undefined behaviour.

Remove this assignment, thread handles aren’t 0, so your code will work anyway.

You just need to correct your for loop here. You don’t need to assign a value in the array. When you call pthread_create it will store the thread id in every location of your thread array.

for(int ti = 0; ti < MAX_THREADS; ti++){
        if(tid[ti] == 0){
            pthread_create(&tid[ti], NULL, testprime, NULL);
            //tid[l] = 1;
        }  

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.