Subj : Re: condvar wait / signal on arbitrary object To : comp.programming.threads From : Michael B Allen Date : Wed Jul 13 2005 10:20 pm On Tue, 12 Jul 2005 22:47:59 -0700, Chris Thomasson wrote: >> Or (I'm not certain that this actually makes sense but ...) each condvar >> could have its own mutex. >> >> struct ctx { >> pthread_cond_t condvars[CTX_ARRAY_SIZE]; >> pthread_mutex_t mutexes[CTX_ARRAY_SIZE]; >> }; >> ... >> int >> ctx_pthread_cond_wait(struct ctx *ctx, void *obj) >> { >> int idx = (size_t)obj % CTX_ARRAY_SIZE; >> pthread_cond_t *cond = ctx->condvars[idx]; >> pthread_mutex_t *mutex = ctx->mutexes[idx]; >> return pthread_cond_wait(cond, mutex); >> } > > You can get into potential deadlock situations here, if your not careful... Ah, yes. Nicely illustrated. The condvars can be "shared" only because they have the property that extra wakeups do not threaten deterministic behavior. The mutexes OTOH are a different concept and therefore this "incedental sharing" technique simply does not apply. Mike > static ctx locks; > > > static obj a, b, c; > > > Thread A > ---------- > > 1: ctx_pthread_mutex_lock( &locks, &a ); > 2: ctx_pthread_mutex_lock( &locks, &b ); > 3: ctx_pthread_mutex_unlock( &locks, &b ); > 4: ctx_pthread_mutex_unlock( &locks, &a ); > > > > Thread B > ---------- > > 1: ctx_pthread_mutex_lock( &locks, &b ); > 2: ctx_pthread_mutex_lock( &locks, &c ); > 3: ctx_pthread_mutex_unlock( &locks, &c ); > 4: ctx_pthread_mutex_unlock( &locks, &b ); > > > > > Lets say that the objects map to the following mutexs: > > &a = mutex1 > &b = mutex2 > &c = mutex1 > > > > and the execution sequence happens to go like this: > > A1 > B1 > A2 -- deadlocked! > ... .