0
void createThreads(int k){
struct threadData threadData[k];

int numThreads = k;
int i = 0;
int err = 0;

pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
for(i = 0;i<numThreads;i++){

    threadData[i].thread_id = i;
    threadData[i].startIndex = ((N/k)*i);
    threadData[i].stopIndex = ((N/k)*(i+1));

    err = pthread_create(&threads[i], NULL, foo, (void *)&threadData[i]);


    if(err != 0){
        printf("error creating thread\n");
    }
}
}

Here, N and k are integers where the remainder of N/k is guaranteed to be 0. including createThreads(numThreads); in main will cause my program to seg fault and commenting it out will take care of this however any printf debug statements I put into createThreads (even on the first line inside the function) will not show so I am pretty confused as to how to debug this. All help is appreciated.

2
  • It's not the cause of your problem, but why are you using malloc in C++? Commented Mar 15, 2015 at 22:58
  • struct threadData threadData[k]; This is not legal C++. You can't create an array using a variable as the number of entries. Commented Mar 15, 2015 at 23:03

1 Answer 1

2

I suppose the problem is that your arg parameter is on stack of your createThreads function:

struct threadData threadData[k];

so once your thread gets created and run, and createThreads returns, threadData is no longer valid, so your thread function should not touch argument data. Otherwise its undefinded behaviour and crash.

so to fix it, you should either, make threadData global (outside createThreads), or malloc it.

Sign up to request clarification or add additional context in comments.

1 Comment

This is definitely a problem. But there can also be further problems in foo itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.