linux下的信号量操作示例

    技术2022-05-20  61

    #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)