This is the mail archive of the guile@cygnus.com mailing list for the guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: condition variables and mutexes


Hi there, 

 > Maybe it would be more useful to pass the mutex as part of the
 > condition variable constructor.

Well, in Scheme programming, it would be.  However, in C programming,
there is a good reason why the condition variable is implemented
independent with mutex.  Here is my understanding.

As you said, a condition variable is used associated with exactly one
mutex.  Like this:

	pthread_mutex_lock (mutex_p);
	...
	while (some_condition_not_match)
		pthread_cond_wait (cond_p, mutex_p);
	...
	pthread_mutex_unlock (mutex_p);

The potion of code within mutex_lock and mutex_unlock is called
"critical region" and it should not be too long.

Please note that in usual case, the reference of mutex_p is quite near
by the call of cond_wait, and it is highly likely on register or on
data-cache.  (In some cases, mutex_lock, mutex_unlock, and cond_wait
would be expanded in-line.)  Hence, the argument mutex_p of cond_wait
costs almost nothing for data reference.

If the condition variable was implemented associated with mutex, the
size of condition variable would be bigger.  And cond_wait would cause
(useless) memory fetch for mutex, and result waste of data cache.

In short, as a condition variable is always associated with its mutex,
the implementation of condition variable doesn't need to know about
its mutex.  For cond_wait, mutex is (almost always) on register or
data cache.
--