Subj : Re: Condition variables & mutexes To : comp.programming.threads From : Ian Pilcher Date : Wed Jan 26 2005 08:53 am Torsten Robitzki wrote: > > As you don't use the mutex to prevent the threads from accessing shared > data, it's probably "overkill" ;-). With a condition variable you can > wait for a user defined predicate to become true. And you should wait > for the predicate in a loop testing the predicate to become true. If you > change the shared data you should do it with the mutex at hand and > signal the condition variable if the predicate became true due to your > change. This would result in something like this: > Thank you so much for the example. Here is my new (working) code: #include #include #include static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static volatile int thread_is_ready = 0; static void *thread(void *arg) { pthread_mutex_lock(&mutex); thread_is_ready = 1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); return NULL; } int main(void) { pthread_t tid; pthread_create(&tid, NULL, thread, NULL); pthread_mutex_lock(&mutex); while (!thread_is_ready) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); return 0; } > > but it's hard to see, why you don't just join the thread. > Well, it's just an example. I'm trying to roll my own pthread-safe version of alarm(). My pt_alarm_init() function creates a new thread, and that thread needs to do a little bit of initialization before pt_alarm_init() returns. My plan is to use a condition variable to achieve this. Is there a better way? Thanks! -- ======================================================================== Ian Pilcher i.pilcher@comcast.net ======================================================================== .