当前位置:网站首页>[interprocess communication IPC] - semaphore learning
[interprocess communication IPC] - semaphore learning
2022-07-27 08:50:00 【I am sixteen years old】
Catalog
3、 ... and : The classification of semaphores
5、 ... and : Semaphore code learning
One : Understand semaphores
•Dijkstra Proposed “ Semaphore ” The concept is co distribution procedure ( Two processes are accessing the same order at the same time ) A major advance in the field of design• A semaphore is a variable , It can only take positive integer values , There are only two operations on these positive integers : Wait and signal• These two operations of semaphores are represented by two symbols :P(semaphore variable) For waiting -1
V(semaphore variable) For signals +1
Data running at the same time is not safe -- Semaphore
Threads : Multiple threads access the same data source at the same time , There will be thread synchronization problems
Thread synchronization solution : Mutex of threads The semaphore of the thread 【 Thread lock 】【 Multiple threads in a process 】【 Thread lock solves the internal problems of the process 】
process : Multiple processes access the same data source at the same time , There will be a problem of process co sending program design
Solution to the security problem of process data sharing :IPC Semaphore 【 Process lock 】【 Multiple threads in different processes 】【 The process lock solves the external problems of the process 】
Two :pv operation
Suppose we have a semaphore variable sv, be pv Operation of the
The definition is as follows
•P(sv): If sv The value of is greater than zero , Just subtract from it 1; If sv The value of is equal to zero , Just hang up 【 Blocking 】 The implementation of the process 【P Operate the lock 】•V(sv): If there are other processes waiting sv Variable is suspended , Let it resume execution ; If there is no process due to waiting sv Variable is suspended , Just add 1【V Operation unlocking 】
3、 ... and : The classification of semaphores
• The simplest semaphore is one that can only take “0” and “1” Variable of value , That's what people often say “ Binary semaphores ”【 Make a lock 】• Semaphores that can take a variety of positive integer values are called “ General semaphore ”【 Make a notice , But semaphore Message queuing is better 】
Four : Semaphore function
Message queue :msgget( establish / visit ) msgctl( Delete ) msgsnd( send out ) msgrcv( receive )
Shared memory :shmget( establish / visit ) shmctl( Delete ) shmat( Connect ) shmdt( To break off )
Semaphore :semget( establish / visit ) semctl( Delete ) semop(P and V operation )
• Each semaphore function can operate on groups of general semaphores , Naturally, it can also complete the operation of the simplest binary semaphore• You often need to use header files <sys/types.h> and <sys/ipc.h>
int semctl(int sem_id,int sem_num,int command,...);
int semget(key_t key,int num_sems,int sem_flags);
int semop(int sem_id,struct sembuf * sops,size_t nsops);
Function name :semget function
Function function : Create a new semaphore or get the key word of an existing semaphore
Function parameter :int semget (key_t key,int num_sems,int sem_flag);
•key: It's an integer , Unrelated processes will access the same through this value Semaphore•num_sems: Number of semaphores to be used , It almost always takes the value 1•sem_flags: It's a set of signs , Its function and open The various flags of functions are very similar , Its low-end nine bits are the permission of the semaphore , Its function is equivalent to the access rights of files , Can be associated with key values IPC_CREATE Do bit by bit OR Operation to create a new semaphore (IPC_CREAT|0766)The function returns : A positive value will be returned on success , It is the identification code used by other semaphore functions , If you fail , Will return -1
Function name :semop function
Function function : Change the key value of the semaphore
Function parameter :int semop ( int sem_id, struct sembuf *sem_ops,size_t num_sem_ops,);
•sem_id: Is the identification code of the semaphore , That is to say semget The return value of the function•sem_ops: Is a pointer to a structure value•Semop All actions called are completed at one time , This is to avoid possible competition due to the use of multiple semaphoresAmong them
sembuf Elements in structure
struct sembuf{
short sem_num;
short sem_op;
short sem_flg;
};
•sem_num Is the number of the semaphore , If you don't need to use a set of semaphores for your work , This value is generally taken as 0.•sem_op It's a semaphore once PV The value added or subtracted during operation , Generally, only two values are used , One is “-1”, That is to say P operation , Wait for the semaphore to become available ; The other is “+1”, That's our V operation , Semaphores have become available•sem_flag Usually set to SEM_UNDO. She will make the operating system track the changes made to the semaphore by the current process
Function name :semctl function
Function function : Information that allows us to directly control semaphores
Function parameter :int semctl(int sem_id,int sem_num,int command,…);
•sem_id: By semget Function returns a semaphore identification code•sem_num: The number of the semaphore , If you need to use groups of semaphores in your work , You need this number ; It is generally taken as 0, Indicates that this is the first and only semaphore•comman: Action to be taken• If there is a fourth parameter , Then it will be a “union semun” Composite structure• Delete semctl(sem_id,0,IPC_RMID);semctl Function command There can be many different values , The following two are more commonly used :
•SETVAL: Used to initialize a semaphore to a known value , This value is in the semun In the structure val The member's face is passed on .
•IPC_RMID: Delete a semaphore identification code that is no longer used
5、 ... and : Semaphore code learning
Create two projects Represents two processes

#include<iostream>
#include<stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include<unistd.h>
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) */
};
// Semaphore creation
int sem_create(key_t key, int num_sems)
{
int res = 0;
res = semget(key,num_sems, IPC_CREAT | 0777);
if (res < 0)
{
perror("semget error");
}
return res;
}
// The semaphore is assigned an initial value
int sem_setVal(int semid, int semindex, int val)
{
union semun arg;
arg.val = val;
int res = semctl(semid, semindex, SETVAL, arg);
if (res < 0)
{
perror("semctl error");
}
return res;
}
// Semaphore P operation -1
int sem_p(int sem_id, int semindex)
{
struct sembuf buf = { semindex,-1,SEM_UNDO };
int res = semop(sem_id, &buf, 1);
if (res < 0)
{
perror("semop error");
}
return res;
}
// Semaphore V operation +1
int sem_v(int sem_id, int semindex)
{
struct sembuf buf = { semindex,1,SEM_UNDO };
int res = semop(sem_id, &buf, 1);
if (res < 0)
{
perror("semop error");
}
return res;
}
int main()
{
// Semaphore creation
int semid = sem_create((key_t)1003, 1);
// Semaphore 0 Subscript sets the initial value 1
sem_setVal(semid, 0, 1);
// Lock
sem_p(semid, 0);
for (int i = 0; i < 30; i++)
{
cout << " The first engineering process ----------" << i << endl;
sleep(1);
}
// Unlock
sem_v(semid, 0);
return 0;
}
#include<iostream>
#include<stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include<unistd.h>
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) */
};
// Semaphore creation
int sem_create(key_t key, int num_sems)
{
int res = 0;
res = semget(key, num_sems, IPC_CREAT | 0777);
if (res < 0)
{
perror("semget error");
}
return res;
}
// Semaphore P operation -1
int sem_p(int sem_id, int semindex)
{
struct sembuf buf = { semindex,-1,SEM_UNDO };
int res = semop(sem_id, &buf, 1);
if (res < 0)
{
perror("semop error");
}
return res;
}
// Semaphore V operation +1
int sem_v(int sem_id, int semindex)
{
struct sembuf buf = { semindex,1,SEM_UNDO };
int res = semop(sem_id, &buf, 1);
if (res < 0)
{
perror("semop error");
}
return res;
}
int main()
{
// Semaphore access
int semid = sem_create((key_t)1003, 1);
// Lock
sem_p(semid, 0);
for (int i = 0; i < 30; i++)
{
cout <<"-------------- The second engineering process ----------" << i << endl;
sleep(1);
}
// Unlock
sem_v(semid, 0);
return 0;
}result :
After the first process is executed , The second process can be started
ipcs Check it out. When the process is running , Semaphores always exist
You need to wait for the two processes to finish running , Can pass ipcrm -a To delete semaphores

边栏推荐
- 691. Cube IV
- Realization of background channel group management function
- Function realization of order system
- 低成本、低门槛、易部署,4800+万户中小企业数字化转型新选择
- “鼓浪屿元宇宙”,能否成为中国文旅产业的“升级样本”
- 02 linear structure 3 reversing linked list
- Day3 -- flag state holding, exception handling and request hook
- General Administration of Customs: the import of such products is suspended
- 海关总署:这类产品暂停进口
- Realize SPU management in the background
猜你喜欢

4276. Good at C

"Weilai Cup" 2022 Niuke summer multi school training camp 1

redis 网络IO

微信安装包从0.5M暴涨到260M,为什么我们的程序越来越大?

Day5 - Flame restful request response and Sqlalchemy Foundation

Use of flask

Initial summary of flask framework creation project

Day4 --- flask blueprint and rest ful

Day3 -- flag state holding, exception handling and request hook

Digital intelligence innovation
随机推荐
N queen problem (backtracking, permutation tree)
Openresty + keepalived to achieve load balancing + IPv6 verification
Matlab画图技巧与实例:堆叠图stackedplot
Implementation of registration function
【Flutter -- GetX】准备篇
海关总署:这类产品暂停进口
接口测试工具-Jmeter压力测试使用
“鼓浪屿元宇宙”,能否成为中国文旅产业的“升级样本”
Unity3D 2021软件安装包下载及安装教程
MySQL基础知识学习(一)
永久设置source的方法
4278. 峰会
Implementation of queue (sequential storage, chain storage)
Flask request data acquisition and response
Day6 --- Sqlalchemy advanced
Create a project to realize login and registration, generate JWT, and send verification code
Day4 --- flask blueprint and rest ful
Management of product pictures
2034: [Blue Bridge Cup 2022 preliminary] pruning shrubs
Flask's operations on model classes