2011-04-05 29 views
2

我需要帮助构建一个实现信号量的监视器,并且简单的C示例将会执行。并发性 - 实现信号量的监视器

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

+0

可以使用条件变量吗? – Karmastan 2011-04-06 01:49:55

+0

@Karmastan:是的。 – 2011-04-06 02:18:57

+0

[监视器上的Wikipedia页面](http://en.wikipedia.org/wiki/Monitor_%28synchronization%29)包含这样一个例子。 – caf 2011-04-06 05:41:10

回答

7

如果你说互斥/条件变量是允许的,然后检查:

#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

这是对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 
    } 
}