使用sem_post信号量进行线程同步

写了一小段程序,测试一下线程同步的问题,如下:

#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

sem_t sp; 

int val = -1;
int semPost(sem_t * pSem, int nMaxCount)
{
    int nRet, nSemCount;

    sem_getvalue(pSem, &nSemCount);
    if (nSemCount>=nMaxCount)
    {
        return 0;
    }
    else
    {
        nRet=sem_post(pSem);
        return nRet;
    }
}

int semWait(sem_t * pSem)
{
    int nRet;
    nRet=sem_wait(pSem);

    while (sem_trywait(pSem)==0) {}
    return nRet;
}

void xxx()
{
    while(1)
    {
        semWait(&sp);
        printf("xxx  val  %d
",val);
    }

}

void yyy()
{
    int i = 0;
    while(1)
    {
    //    semPost(&sp,3);
        printf("yyy :  %d
",i);
        sleep(1);
        if(i++ >= 3)
        {
            i = 0;
            semPost(&sp,3);
            val = 9;
            printf("now xxx can run !!!
");
        }
    }

}

int main(int argc,char **argv)
{
    pthread_t x;
    pthread_t y;

    sem_init(&sp,0,0);

    pthread_create(&x,NULL,(void *)xxx,NULL);
    pthread_create(&y,NULL,(void *)yyy,NULL);

    while(1)
    {
        sleep(1);
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/xiaowenhu/p/3160884.html