Koalano
November 24th, 2009, 04:28 AM
Hi! I'm new to thead programming and I have a question.
I'm reading an example. This example illustrates condition variables in the context of producers and consumers. You create a producer thread that creates work and then N consumer threads that operate on the (simulated) work.
Here is a code snippet of one of the consumers:
while( 1 ) {
assert( pthread_mutex_lock( &cond_mutex ) == 0);
assert( pthread_cond_wait( &condition, &cond_mutex )
== 0 );
if (workCount) {
workCount—;
printf( “Consumer %x: Performed work (%d)\n”,
pthread_self(), workCount );
}
assert( pthread_mutex_unlock( &cond_mutex ) == 0);
}My question is why do we have to use assert() in this snippet? In this case, the consumer will abort if the mutex is not available.
If we don't use assert(), the consumer just waits for the mutex to be available and then do the work. Wouldn't this be the behavior we expect from a consumer?
Thanks for reading my question.
Regards,
Koalano
I'm reading an example. This example illustrates condition variables in the context of producers and consumers. You create a producer thread that creates work and then N consumer threads that operate on the (simulated) work.
Here is a code snippet of one of the consumers:
while( 1 ) {
assert( pthread_mutex_lock( &cond_mutex ) == 0);
assert( pthread_cond_wait( &condition, &cond_mutex )
== 0 );
if (workCount) {
workCount—;
printf( “Consumer %x: Performed work (%d)\n”,
pthread_self(), workCount );
}
assert( pthread_mutex_unlock( &cond_mutex ) == 0);
}My question is why do we have to use assert() in this snippet? In this case, the consumer will abort if the mutex is not available.
If we don't use assert(), the consumer just waits for the mutex to be available and then do the work. Wouldn't this be the behavior we expect from a consumer?
Thanks for reading my question.
Regards,
Koalano