I have a problem with pthreads in my C++ application.
In my main function I have:
int main(){
...
for(i=0; i<numberOfThreads; i++){
arg[0]=i;
pthread_create(&tidVec[i], NULL, &thread_body, (void*) arg);
cout << "tidVec[" << i <<"]: " << tidVec[i] << " arg[0]: " << arg[0] << endl;
}
...
}
And in my thread_body function:
void * thread_body(void* arg){
...
int* a = (int*)arg;
cout << "tid: " << pthread_self() << " no.thread: " << a[0] << endl;
...
}
The output to this (e.g. with numberOfThreads=2) appears to be:
tidVec[0]: 2932403008 arg[0]: 0
tidVec[1]: 2924010304 arg[0]: 1
tid: 2924010304 no.thread: 1
tid: 2932403008 no.thread: 1
In a more general case, with numberOfThreads=n, no.thread is equal to n-1, for all threads. Could you please help me figure out why? Is there something I don't understand in how you use the start routine?
Thank you for your time.
There's a data race in your code since you pass the address of the same location (
arg[0]
) to all threads here:You probably meant to use:
instead. And the same applies to prints you do in the loop.