I'm new at threading I want to use ptherad_cond_signal & pthread_cond_wait to check some condition I have this code as a sample:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int x = 0;
void* f1(void *arg){
for (int i = 0; i < 10; i++)
{
pthread_mutex_lock(&lock);
x += 10;
printf("%d\n", x);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
return NULL;
}
void* f2(void* arg){
pthread_mutex_lock(&lock);
while (x < 40)
{
pthread_cond_wait(&cond, &lock);
}
x -= 40;
pthread_mutex_unlock(&lock);
return NULL;
}
int main(int argc, char *args[]){
pthread_t p1, p2;
pthread_create(&p2, NULL, f2, NULL);
pthread_create(&p1, NULL, f1, NULL);
pthread_exit(NULL);
return 0;
}
result:
10
20
30
40
50
60
70
80
90
100
but I expect:
10
20
30
40
10
20
30
40
50
60
why after pthread_cond_signal, function f2 doesn't continue?
It seems in f1 for loop, locks again before pthread_cond_wait wakeing up