mercredi 25 mars 2015

Why pthread_condition variable getting hanged?


I just started learning pthread condition variable. But below code is not working as expected.



#include<iostream>
#include<pthread.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER;
int count=0;


void *inc_func(void *arg)
{
pthread_mutex_lock(&mutex);
int c;

while(1)
{
cin>>c;
if(c==8){
pthread_cond_signal(&count_threshold_cv);break;}
}

cout<<"inc count reached 8"<<endl;
pthread_mutex_unlock(&mutex);

}

void *watch(void *arg)
{
pthread_mutex_lock(&mutex);
while(1){
pthread_cond_wait(&count_threshold_cv,&mutex);
break;
}
cout<<"This executed"<<endl;
pthread_mutex_unlock(&mutex);
}

int main()
{
pthread_t id[26];
pthread_create(&id[0],NULL,inc_func,NULL);
pthread_create(&id[1],NULL,watch,NULL);

int i;
for(i=0;i<2;i++)
{
pthread_join(id[i],NULL);
}

}


when the input is 8 this code gets hanged at "inc count reached 8? I am not able to understand. Where is my understanding wrong?




Aucun commentaire:

Enregistrer un commentaire