Reputation: 31
#include<pthread.h>
#include<stdio.h>
#include <errno.h>
pthread_cond_t done;
pthread_mutex_t mutex;
void*cond_wait(void*p){
while(1){
printf("%dwait\n",(int)p);
pthread_cond_wait(&done,&mutex);
printf("%dwakeup\n",(int)p);
}
}
int main(){
int status;
int i=1;
pthread_t p;
status=pthread_mutex_init(&mutex,NULL);
pthread_mutex_lock(&mutex);
pthread_cond_init(&done,NULL);
pthread_create(&p,NULL,cond_wait,(void*)1);
while(1){
sleep(1);
pthread_cond_signal(&done);
}
}
The thread just wake up and is not blocked by the mutex because it doesn't call call pthread_cond_wait without locking mutex.Is it right?
Upvotes: 0
Views: 776
Reputation: 239011
If you call pthread_cond_wait()
without the calling thread having already locked the mutex, the program has undefined behaviour. Anything could happen, including a crash.
Upvotes: 1