当前位置:网站首页>15.8 the semaphore Unix environment programming chapter 15
15.8 the semaphore Unix environment programming chapter 15
2022-08-09 10:29:00 【Mary Soda Meatloaf】
A semaphore, unlike IPC, is a counter that provides multiple processes with access to a shared data object.
In order to obtain a shared resource, a process needs to do the following:
- Test the semaphore that controls the resource.
- If the value of this semaphore is positive, the process can use the resource, in which case the process will decrement the semaphore value by 1, indicating that it uses one resource unit.
- If the value of this semaphore is 0, the process goes to sleep until the value of the semaphore is greater than 0.
When a process is not using a shared resource controlled by a semaphore, the semaphore value is incremented by 1.If any processes are sleeping waiting for this semaphore, wake them up.The increment and decrement of the semaphore value is an atomic operation.
A common form of semaphore is called a binary semaphore, which controls a single resource and has an initial value of 1.
When we want to use XSI semaphore, we first need to get a semaphore ID by calling the function semget.
#include int semget(key_t key,int nsems,int flag);//Successful return semaphore ID, error return -1
nsems is the number of semaphores in this collection, if creating a new collection, nsems must be specified.If referring to an existing collection (a client process), specify 0 for nsems.
The smectl function includes a variety of semaphore operations
#include int semctl(int semid,int semnum,int cmd,...)
The fourth parameter is optional, its use depends on the command requested, if it is used, its type is senum, which is a union of several command-specific parameters:
union semun{int val; /*for SETVAL*/struct semid_ds *buf; /*for IPC_STAT and IPC_SET*/unsigned short *array;/*for GETALL and SETALL*/}
The function semop automatically executes the operation data on the semaphore collection
#include int semop(int semid,struct sembuf semoparray[],size_t nops);//successful return 0, error return -1
The parameter semoparray is a pointer to a semaphore operation array represented by a sembuf structure:
struct sembuf{unsigned short sem_num;short sem_op;short sem_flg;}
The parameter nops specifies the number of operations in the array.
边栏推荐
猜你喜欢
随机推荐
Electron application development best practices
【MySQL】mysql因为字符集导致left join出现Using join buffer (Block Nested Loop)
Battery modeling, analysis and optimization (Matlab code implementation)
3D printed this DuPont cable management artifact, and the desktop is no longer messy
百度云大文件网页直接下载
conditional control statement
xmms播放器加了播放列表的管理功能
Tom Morgan | Twenty-One Rules of Life
编程技术提升
Nodejs服务端
收到人生第一笔五位数工资
深度学习--自编码器(AutoEncoder)
Attentional Feature Fusion
1001 害死人不偿命的(3n+1)猜想 (15 分)
OneNote 教程,如何在 OneNote 中搜索和查找笔记?
function two
GeoScene Pro 2.1下载地址与安装基本要求
electron 应用开发优秀实践
认识
numpy的ndarray取数操作