信号量定义及实例讲解

2020-03-07  本文已影响0人  布灵不灵的丙丙

信号量

引用:

作用:

实现:

函数定义

#include <semaphore.h>
int sem_int(sem_t *sem, unsigned int value);
void P(sem_t *sem) 
{
    if (sem_wait(sem) < 0)
     unix_error("P error");
}
void V(sem_t *sem)
{
    if (sem_post(sem) < 0)
    unix_error("V error");
}

使用信号量解决读者写者问题:

描述:
应用场景
第一类读者写者问题(读者优先)
int readcnt;    /* Initially = 0 */
sem_t mutex, w; /* Both initially = 1 */

void reader(void) 
{
    while (1) {
        P(&mutex);
        readcnt++;
        if (readcnt == 1) /* First in */
            P(&w);          
        V(&mutex);          

        /* Critical section */
        /* Reading happens  */

        P(&mutex);
        readcnt--;
        if (readcnt == 0) /* Last out */
            V(&w);
        V(&mutex);
    }
}
/* $end reader1 */

/* $begin writer1 */
void writer(void) 
{
    while (1) {
        P(&w);

        /* Critical section */
        /* Writing happens  */ 

        V(&w);
    }
}
/* $end writer1 */
第一类读者写者问题(写者优先)
/* Global variables */
sem_t sem;    /* Initially = N */
sem_t wmutex; /* Initially = 1 */

void reader(void) 
{
    while (1) {
        P(&sem);

        /* Critical section: */
        /* Reading happens   */

        V(&sem);
    }
}

void writer(void) 
{
    int i;

    while (1) {
        P(&wmutex);
        for (i=0; i<N; i++)
            P(&sem);
        V(&wmutex);

        /* Critical section: */
        /* Writing happens   */

        for (i=0; i<N; i++)
            V(&sem);
    }
}
/* $end rw3 */
上一篇下一篇

猜你喜欢

热点阅读