【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! \n";

    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

 

 

 

  

posted on   崔好好  阅读(4132)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示