【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

 

  

原文地址:https://www.cnblogs.com/cuish/p/4133919.html