• 【Linux】Semaphore信号量线程同步的例子


     

    0、 信号量

    Linux下的信号量和windows下的信号量稍有不同。

     

    Windows

    Windows下的信号量有一个最大值和一个初始值,初始值和最大值可以不同。  而且Windows下的信号量是一个【内核对象】,在整个OS都可以访问到。

     

    Linux

    Linux下的信号量在创建的时候可以指定一个初始值,这个初始值也是最大值。 而且Linux下的信号量可以根据需要设置为是否是【进程间共享】的,如果不是进程间共享的则就是一个本进程局部信号量。

     

     1、相关API

    int semt_init(
     semt_t* sem,     //a semaphore pointer
     int     pshared, //0 as a local semaphore of cuurent process, or the semaphore can be shared between mulit processes
     unsigned value   //the init  value of this memaphore
     )
    
    
    //minus ONE  value of semaphore
    int sem_wait(sem_t* sem);
    
    //add ONE value of semaphore
    int sem_post(sem_t* sem);
    
    
    //destroy the semaphore
    int sem_destroy(sem_t* sem);
    
    All  the functions above Rerurn ZERO  IF SUCCESS !

    2、上代码

     这个demo创建了5个线程,信号量的初始值为2,即同时最多有2个线程可以获得获得信号量从而得到执行。

    #include <iostream>
    #include <pthread.h>
    #include <unistd.h>
    #include <semaphore.h>
    using namespace std;
    
    sem_t g_semt;
    
    void* work_thread(void* p)
    {
        pthread_t tID = pthread_self();
    
        cout << "-------" << tID << " is waiting for a semaphore -------" << endl;    
        sem_wait(&g_semt);
        cout << "-------" << tID << " got a semaphore, is Runing -------" << endl << endl;
        usleep(1000 * 1000 * 2);  //2 seconds
        sem_post(&g_semt);
    
        static char* pRet = "thread finished! 
    ";
    
        return pRet;
    }
    
    int main()
    {
        const size_t nThreadCount = 5; //amounts of thread array
        const unsigned int nSemaphoreCount = 2; //initial value of semaphore
        int nRet = -1;
        void* pRet = NULL;
        pthread_t threadIDs[nThreadCount] = {0};
        
        nRet = sem_init(&g_semt, 0, nSemaphoreCount);
        if (0 != nRet)
            return -1;
    
        for (size_t i = 0; i < nThreadCount; ++ i)
        {
            nRet = pthread_create(&threadIDs[i], NULL, work_thread, NULL); 
            if (0 != nRet)
                continue;
        }
    
        for (size_t i = 0; i < nThreadCount; ++ i)
        {
            int nRet2 = pthread_join(threadIDs[i], &pRet);
            cout << endl << threadIDs[i] << " return value is " << (char*)pRet << endl;
        }
    
        cout << endl << endl;
    
        sem_destroy(&g_semt);
    
        return 0;
    }

     

       

     

     

    4、执行情况

     编译 g++ -D_REENTRANT  -lpthread   semaphore.cpp  -g  -o  semaphore.out

     

      

  • 相关阅读:
    系统兼容性与软件兼容性
    SqlServer 笔记三 规则
    Sql Server 2008 与 Visual Studio 2008 安装说明
    Ms Sql Server
    Git系列教程三 配置与基本命令
    Git系列教程一 入门与简介
    Git系列教程二 基础介绍
    浏览器IE与非IE区分
    SqlServer 笔记二 获取汉字的拼音首字母
    时间戳与日期字符串的转换
  • 原文地址:https://www.cnblogs.com/cuish/p/4133919.html
Copyright © 2020-2023  润新知