我需要帮助构建一个实现信号量的监视器,简单的 C 示例就可以。
这是为了证明可以在任何可以使用信号量的地方使用监视器。
最佳答案
如果您说允许使用互斥锁/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;
}
关于并发 - 实现信号量的监视器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5558921/