For questions 29–30, consider the following producer/consum…
For questions 29–30, consider the following producer/consumer implementation using a shared bounded buffer of size 1. There are two producer threads and two consumer threads. Assume the mutex and condition variable are correctly initialized. The variable count tracks the number of items in the buffer (initially 0). int count = 0; mutex_t m; cond_t cv; void *producer(void *arg) { while (1) { mutex_lock(&m); // P1 if (count == 1) // P2 cond_wait(&cv, &m); // P3 count = 1; // P4 fill_buffer(); // P5 cond_signal(&cv); // P6 mutex_unlock(&m); // P7 } } void *consumer(void *arg) { while (1) { mutex_lock(&m); // C1 if (count == 0) // C2 cond_wait(&cv, &m); // C3 count = 0; // C4 use_buffer(); // C5 cond_signal(&cv); // C6 mutex_unlock(&m); // C7 } }
Read DetailsFor questions 23–24, consider the following code snippet: i…
For questions 23–24, consider the following code snippet: int bytesLeft = MAX_HEAP_SIZE; cond_t c; mutex_t m; void* allocate(int size) { mutex_lock(&m); while (bytesLeft < size) cond_wait(&c, &m); void *ptr = ...; // get mem from heap bytesLeft -= size; mutex_unlock(&m); return ptr; } void free(void *ptr, int size) { mutex_lock(&m); bytesLeft += size; cond_signal(&c); mutex_unlock(&m); }
Read Details