Navin Shrinivas
Navin Shrinivas

Reputation: 35

pthreads_create causing segment faults for no apparent reason

i have been writing some function that needs to multile threaded in C , pthreads seemed like a no brainer.But now that i have written it out it is giving my segment faults all the time , with a bunch of printf() statements and commenting out part of codes i figured out that pthread_create is causing these , any help would be appreciated! As far as i can see me passing in the parameters to pthread_create seems perfectly fine.

code :

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdbool.h>
typedef unsigned long long ll;
struct opscount{
    ll faddpthread;
    ll fsubpthread;
    ll fmulpthrea;
    ll fdivpthread;
};
int main(){
    int total_thread,time;
    printf("Enter total number of threads : ");
    scanf("%i",&total_thread);
    printf("Time to run the test : ");
    scanf("%i",&time);
    struct opscount opcount[total_thread];
    pthread_t thread[total_thread];
    //---------------------start of fadd test----------------------------------
    for(int i=0;i<total_thread;i++)
    {
        opcount[i].faddpthread=0;
        pthread_create(&thread[i],NULL,faddtf,opcount+i);
    }
    int optime=time/4;
    sleep(optime);
    for(int i=0;i<total_thread;i++)
    {
        pthread_cancel(thread[i]);// kills the threads
    }
}

the thread function being :

void *faddtf(void *oppthread)
{
    double c=0.75665;
    while(true)
    {
        c+=v1+v2+v3+v4+v5;
        ((struct opscount *)oppthread)->faddpthread+=5;
    }
}

Upvotes: 1

Views: 53

Answers (1)

David Schwartz
David Schwartz

Reputation: 182779

The code has two bugs.

One is that the thread that runs main can terminate, destroying the stack on which opcount exists. This can happen before the threads have actually had a chance to terminate. You don't wait for them to terminate. (And they won't terminate because of the second bug.)

The second bug is that the threads you try to cancel don't have any way to be cancelled. They don't check if they've been cancelled. They don't enable async cancellation.

What's likely happening is your code crashes when the threads access objects on the first thread's stack after the first thread has terminated and succeeds if, by luck, the process terminates before that happens because returning from main terminates the process.

Upvotes: 2

Related Questions