zoukankan      html  css  js  c++  java
  • 使用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;
    }
  • 相关阅读:
    云网站 SEO
    GraphQL 开发原则
    软件秘钥实现
    删除文件
    GUI 桌面程序开发
    chcon SeLinux
    正确使用 cookie 的 path
    struts 2用DomainModel接收参数
    Struts 2动态调用方法(DMI)
    struts 2actionwildcard 通配符配置
  • 原文地址:https://www.cnblogs.com/xiaowenhu/p/3160884.html
Copyright © 2011-2022 走看看