2
세마포어를 구현하는 모니터를 구성하는 데 도움이 필요하며 간단한 C 예가 도움이됩니다.동시성 - 세마포를 구현하는 모니터
이것은 모니터가 세마포어를 사용할 수있는 모든 장소에서 사용될 수 있음을 보여줍니다. 당신이 뮤텍스/condvars이 허용되는 말한다면
세마포어를 구현하는 모니터를 구성하는 데 도움이 필요하며 간단한 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;
}
이것은 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
}
}
조건 변수를 사용해도 되니? – Karmastan
@Karmastan : 예. –
[모니터에 대한 Wikipedia 페이지] (http://en.wikipedia.org/wiki/Monitor_%28synchronization%29)에는 이러한 예가 포함되어 있습니다. – caf