linux下的信号量操作示例

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <pthread.h>
#include <errno.h>
#include <vector>
#include <iostream>
using namespace std;
 
union semun {
        int              val;    /* Value for SETVAL */
        struct semid_ds *buf;    /* Buffer for IPC_STAT, IPC_SET */
        unsigned short  *array;  /* Array for GETALL, SETALL */
        struct seminfo  *__buf;  /* Buffer for IPC_INFO
                                    (Linux specific) */
};
 
//工作线程函数
void * workproc(void * param)
{
        int sid = *(int *)param;  //信号量ID
        pthread_t tid = pthread_self();  //线程ID
 
        cout <<"thread " <<tid <<"/t opt 1 is ok!" <<endl; //第一步操作执行完成
 
 //信号量减1
        sembuf b;
        b.sem_num = 0;
        b.sem_op = -1;
        b.sem_flg = 0;
        int ret = semop(sid, &b, 1);
        if (ret != 0)
                return (void *)-1;
 
 //等待信号量变成0
        cout <<"thread " <<tid <<"/t begin wait for all thread ok!" <<endl;
        b.sem_op = 0;
        ret = semop(sid, &b, 1);
        if (ret != 0)
                return (void *)-1;
        cout <<"thread " <<tid <<"/t end wait for all thread ok!" <<endl;
 
 //执行第二步操作
        cout <<"thread " <<tid <<"/t opt 2 is ok!" <<endl;
 
        return 0;
}
 
int main()
{
 //创建信号量
        int sid = semget(IPC_PRIVATE, 1, IPC_CREAT|0660);
        if (sid == -1)
        {
                cout <<"create sem error!" <<endl;
                return -1;
        }
 
 //设置信号量的初始值为5
        semun un;
        un.val = 5;
        int ret = semctl(sid, 0, SETVAL, un);
        if (ret == -1)
                return -1;
 
 //启动一组工作线程
        vector<pthread_t> ids;  //保存启动的线程ID数组
        pthread_t id;
        for (int i = 0; i < 5; ++i)
        {
                pthread_create(&id, NULL, workproc, &sid);
                ids.push_back(id);
        }
 
 //等待所有的工作线程结束
        int num = ids.size();
        for (int i = 0; i < num ; ++i)
        {
                pthread_join(ids[i], NULL);
        }
 
 //删除信号量
        semctl(sid, 1, IPC_RMID);
 
        return 1;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值