yes as stated above mutex makes operations atomic
that is whatever you need to do inside the thread you can do with a lock on a structure a variable whatever
and no other threads can toy with that structure or variable or pointers till you are done.
this doesn't have to be condition variables.
now if you want to use a condition variable to controll your thread (a flag) and others at the same time
you can put a mutex lock on the condition flag like rstewart has shown
however
if we are looking to do something when another thread set the flag we will only lock it when we check the flag
so the other thread can change it
unfurtunately you can end up with a bunch of threads doing loops and eating up cpu cycles
locking and unlocking and checking conditions like crazy waiting to do stuff. (bad)
so you figure you have to use wait
but if we try to use wait doing this we could concievable cause a race condition by fluke scheduling like before we tried mutex at all.
lets say the thread checks the flag (locks and unlocks the mutex) and it's not set. then the schedular interupts and
starts main in the middle of setting the flag. then goes back to the thread and it goes to wait in the wrong place and waits forever.
enter GNU to the rescue with
Code:
int thread_flag = 0;
pthread_cond_t thread_flag_condition;
pthread_mutex_t thread_flag_mutex;
void *thread_function1 (void *thread_arg) {
while(1) {
pthread_mutex_lock (&thread_flag_mutex);
while (!thread_flag)
// now we can just hang here
// it's important to know this atomically unnlocks the mutex and then when signaled reaquires the lock
pthread_cond_wait(&thread_flag_condition, &thread_flag_mutex);
// when we get here we know someone set the flag
pthread_mutex_unlock (&thread_flag_mutex);
do_junk();
// now send the other thread blocked in while (thread_flag) on it's merry way
set_thread_flag(0);
}
return NULL;
}
void set_thread_flag(int flag_value) {
pthread_mutex_lock (&thread_flag_mutex);
thread_flag=flag_value;
pthread_cond_signal(&thread_flag_condition);
// nothing can check the flag till this lock is removed
pthread_mutex_unlock (&thread_flag_mutex);
}
void *thread_function2 (void *thread_arg) {
while(1) {
pthread_mutex_lock (&thread_flag_mutex);
while (thread_flag)
// now we can just hang here
// it's important to know this atomically unnlocks the mutex and then when signaled reaquires the lock
pthread_cond_wait(&thread_flag_condition, &thread_flag_mutex);
// when we get here we know someone set the flag
pthread_mutex_unlock (&thread_flag_mutex);
do_other_junk();
// now send the other thread blocked in while (!thread_flag) on it's merry way
set_thread_flag(1);
}
return NULL;
}