Here's your problem:
for (int t = 0; t < noOfThreads; t++) {
pointer = (int *) t;
rc = pthread_create(&threads[t], NULL, calc, &pointer);
}
You are passing a pointer to pointer
to pthread_create
, and immediately destroying it when it goes out of scope at the end of the loop body. When the created thread starts running and dereferences that pointer, undefined behavior ensues.
You need to either eat some gray-area behavior and encode your integer in the void*
argument to pthread_create
:
void *calc(void *pointer) {
int t = reinterpret_cast<int>(pointer);
// ...
}
// snip
for (int t = 0; t < noOfThreads; t++) {
rc = pthread_create(&threads[t], NULL, calc, reinterpret_cast<void*>(t));
}
or dynamically allocate storage to pass an integer to the thread function.