Параллелизм - монитор, который реализует семафоры - PullRequest
2 голосов
/ 06 апреля 2011

Мне нужна помощь в создании монитора, который реализует семафор, и простой пример C подойдет.

Это необходимо для демонстрации возможности использования монитора в любом месте, где можно использовать семафор.

Ответы [ 2 ]

8 голосов
/ 10 ноября 2011

Если вы говорите, что мьютекс / condvars разрешены, проверьте это:

#include <pthread.h>

typedef struct
{
  unsigned int count;
  pthread_mutex_t lock;
  pthread_cond_t cond;
} semaph_t;

int
semaph_init (semaph_t *s, unsigned int n)
{
  s->count = n;
  pthread_mutex_init (&s->lock, 0);
  pthread_cond_init (&s->cond, 0);
  return 0;
}

int
semaph_post (semaph_t *s)
{
  pthread_mutex_lock (&s->lock); // enter monitor
  if (s->count == 0)
    pthread_cond_signal (&s->cond); // signal condition
  ++s->count;
  pthread_mutex_unlock (&s->lock); // exit monitor
  return 0;
}

int
semaph_wait (semaph_t *s)
{
  pthread_mutex_lock (&s->lock); // enter monitor
  while (s->count == 0)
    pthread_cond_wait (&s->cond, &s->lock); // wait for condition
  --s->count;
  pthread_mutex_unlock (&s->lock); // exit monitor
  return 0;
}
0 голосов
/ 20 марта 2013

Это основной ответ в статье Википедии о мониторах .

monitor class Semaphore
{
  private int s := 0
  invariant s >= 0
  private Condition sIsPositive /* associated with s > 0 */

  public method P()
  {
    if s = 0 then wait sIsPositive
    assert s > 0
    s := s - 1
  }

  public method V()
  {
    s := s + 1
    assert s > 0
    signal sIsPositive
  }
}
...