并发 - 实现信号量的监视器

发布于 2024-10-30 18:28:14 字数 75 浏览 1 评论 0原文

我需要帮助构建一个实现信号量的监视器,简单的 C 示例就可以了。

这是为了证明监视器可以在任何可以使用信号量的地方使用。

I need help constructing a monitor that implements a semaphore, and simple C example will do.

This is to demonstrate that a monitor can be used any place a semaphore can be used.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听不够的曲调 2024-11-06 18:28:14

如果您说允许互斥体/条件变量,请检查以下内容:

#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;
}

If you say mutex/condvars are allowed, then check this:

#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;
}
离线来电— 2024-11-06 18:28:14

这是有关监视器的维基百科文章的主要答案。

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
  }
}

This is the main answer on the Wikipedia article regarding monitors.

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
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文