Segment Fault
Segment Fault

Reputation: 23

Single provider, single consumer. Which is suitable for conditional variable: pthread_cond_t, sem_t or pthread_mutex_t?

There are:

one conditional variable "var": values of var can be 0 or 1 only;

one provider thread "thP": when received data from net, set var 1 (available);

one consumer thread "thC": wait() for var. When got var, set it 0 (unavailable), and process something afterwards.

.

I found two ways to implement this simple model:

(1) Use pthread_cond_t as var. This method needs an additional mutex and a callback function to unlock mutex while thread will be cleaned.

(2) Use sem_t as var. This method may cause a situation as "var>1". thC may do more than one wait() operations to decrease the var's value to 1.

.

Question is:

To implement this simple model "single provider, single consumer, one conditional variable", which type should I use for var, pthread_cond_t, sem_t or simply using pthread_mutex_t as a binary semaphore?

.

Thanks very much!

Upvotes: 2

Views: 402

Answers (1)

bdonlan
bdonlan

Reputation: 231343

For a single consumer, single provider, bounded queue example, the typical was to do this is with one lock protecting two conditional variables (one signalled when 'queue is not full' and one signalled when 'queue is not empty').

The algorithm looks like this:

post(item):
  lock;
  while (queue is full):
    wait(cvar_queue_not_full);
  queue.push(item)
  signal(cvar_queue_not_empty);
  unlock;

consume():
  lock;
  while (queue is empty):
    wait(cvar_queue_not_empty);
  item = queue.shift(item);
  signal(cvar_queue_not_full);
  unlock;
  return item;

This is essentially a bounded semaphore, but allows you to atomically adjust the semaphore and push/pop the queue at the same time. Unfortunately POSIX semaphores are unbounded and do not offer atomicity.

Upvotes: 1

Related Questions