Reputation: 2436
I'm wondering why the following code gives unexpected output: a
can get 110...!
pthread_t th[nbT];
void * func(void *d)
{
while(a<100)
{
pthread_mutex_lock(&l);
cout <<a <<" in thread "<<pthread_self()<<"\n";
a+=1;
pthread_mutex_unlock(&l);
}
return NULL;
}
int main(int argc, const char* argv[])
{
for(int i=0;i<nbT;i++)
pthread_create(&(th[i]), NULL, func, NULL);
for(int i=0;i<nbT;i++)
pthread_join(th[i],NULL);
}
Upvotes: 0
Views: 64
Reputation: 33019
The problem is that you get the lock (mutex) after checking the condition, so you don't know if it's still true or not once you get the lock. You should just do a simple double-check:
while(a<100)
{
pthread_mutex_lock(&l);
cout <<a <<" in thread "<<pthread_self()<<"\n";
if (a<100) a+=1; // <== Added condition here!
pthread_mutex_unlock(&l);
}
Upvotes: 2