Covering Conditions
Let's discuss one last use case of the condition variables, the covering conditions.
We'll cover the following...
We’ll now look at one more example of how condition variables can be used. This code study is drawn from
The problem
The problem they ran into is best shown via simple example, in this case in a simple multi-threaded memory allocation library. Given below is a code snippet that demonstrates the issue.
// how many bytes of the heap are free?int bytesLeft = MAX_HEAP_SIZE;// need lock and condition toocond_t c;mutex_t m;void * allocate(int size) {Pthread_mutex_lock(&m);while (bytesLeft < size)Pthread_cond_wait(&c, &m);void *ptr = ...; // get mem from heapbytesLeft -= size;Pthread_mutex_unlock(&m);return ptr;}void free(void *ptr, int size) {Pthread_mutex_lock(&m);bytesLeft += size;Pthread_cond_signal(&c); // whom to signal??Pthread_mutex_unlock(&m);}
As you might see in the code, when a thread calls into the memory allocation code, it might have to wait in order for more memory to become free. Conversely, when a thread frees memory, it signals that more memory is free. However, this code above has a problem: which waiting thread (there can be more than one) should be woken up?
Consider the following scenario. Assume there are zero bytes free; thread ...