In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is to share with you about what semaphore is in Linux. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Semaphore is usually called semaphore, which can be used to control the number of threads accessing specific resources at the same time, by coordinating each thread to ensure reasonable use of resources.
1. Semaphore semaphore is essentially a counter (no global variable is set because processes are independent of each other, and this may not be seen, nor can it be guaranteed that + + reference counting is an atomic operation). Used for multi-processes to read shared data objects, it is different from pipes, it is not for the main purpose of data transmission, it is mainly used to protect shared resources (semaphores also belong to critical resources) Make resources exclusive to only one process at a time.
two。 How semaphores work because semaphores can only wait and send signals in two ways, namely P (sv) and V (sv), and their behavior is as follows:
(1) P (sv): if the value of sv is greater than zero, subtract it by 1; if its value is zero, suspend the execution of the process
(2) V (sv): if another process is suspended while waiting for sv, let it resume running. If no process is suspended while waiting for sv, add 1.
All PV operations on semaphores are atomic (because it needs to protect critical resources)
Note: atomic operation: the operation of a single instruction is called atomic and the execution of a single instruction will not be interrupted.
3. Binary semaphores (Binary Semaphore) is the simplest type of lock (mutex), which uses only two states: occupied and non-occupied. So its reference count is 1.
4. How does a process obtain a shared resource (1) Test the semaphore that controls the resource
(2) if the value of the semaphore is positive, the process obtains the right to use the resource, and the process subtracts the semaphore by 1, indicating that it uses a resource unit.
(3) if the value of the semaphore is 0, the process enters a suspended state (the process state changes) until the value of the semaphore is greater than 0, and if the process is awakened, return to the first step.
Note: semaphores ensure the consistency of accessing resources through synchronization and mutual exclusion.
5. Functions related to semaphores all functions share header files
# include # include # include5.1 create semaphore int```semget (key_t key, ``int``nsems, ``int``flags) ````/ / returned: signal set ID is returned successfully, error returns-1
(1) the first parameter key is a long integer (the only non-zero). The system must specify an ID value when establishing IPC communications (message queues, semaphores, and shared memory). In general, the id value is obtained through the ftok function, which is changed from the kernel to the identifier. If you want two processes to see the same signal set, you only need to set the key value unchanged.
(2) the second parameter, nsem, specifies the number of semaphores needed in the semaphore set, whose value is almost always 1.
(3) the third parameter flag is a set of flags. When you want to create a new semaphore when the semaphore does not exist, you can set flag to IPC_CREAT to do bitwise or operation with file permissions. When the IPC_CREAT flag is set, even if the key given is an existing semaphore key, no error will be generated. IPC_CREAT | IPC_EXCL can create a new, unique semaphore and return an error if the semaphore already exists. Usually we will return or the last file permission.
5.2 delete and initialize semaphore int```semctl (``int``semid, ``int``semnum, ``int`` cmd,...). If necessary, the fourth parameter is generally set to union semnu arg; as follows
The values used by union semun {int val; / / struct semid_ds * buf; / / IPC_STAT, the cache unsigned short * arry; / / GETALL used by IPC_SET, and the array struct seminfo * _ buf; / / IPC_INFO (unique to Linux) used by SETALL};
(1) sem_id is the semaphore identifier returned by semget
(2) which semaphore of the current semaphore set of semnum
(3) cmd is usually one of two values SETVAL: used to initialize the semaphore to a known value. The value p is set by the val member in union semun, which sets the semaphore before it is used for the first time. IPC_RMID: used to delete a semaphore identifier that no longer needs to be used. If deleted, you don't need default parameters, just three parameters.
5.3 change the value of semaphore int```semop (``int``semid, ``struct``sembuf * sops, ``size_ t``nops);
(1) nsops: the number of operation semaphores, that is, the number of sops structure variables, should be greater than or equal to 1. The most common setting is that this value is equal to 1, and only one semaphore can be operated.
(2) sembuf is defined as follows:
Struct sembuf {short sem_num; / / unless a set of semaphores is used, it is 0 short sem_op / / the data that a semaphore needs to change in an operation, usually two numbers, / / one is-1, that is, P (wait) operation, / / one is + 1, that is, V (send signal) operation. Short sem_flg; / / is usually SEM_UNDO, which makes the operating system track the semaphore, / / and release the semaphore} when the process terminates without releasing the semaphore.
The setting problem of sem_flg in 5.4sembuf is usually set to SEM_UNDO, which enables the operating system to track the semaphore, and when the process terminates without releasing the semaphore, the operating system releases the semaphore, for example, in the binary semaphore, if you do not release the semaphore and exit abnormally, other processes will not be able to apply for the semaphore all the time, but will always be suspended.
The difference between whether or not to set sem_flg to SEM_UNDO
6. Simulate the implementation of semaphores to achieve inter-process communication with a simple example talked about in class:
# include # define total 20 sem_t remain, apple, pear, mutex; static unsigned int vremain = 20, vapple = 0, vpear = 0; void * father (void *); void * mather (void *); void * son (void *); void * daughter (void *); void print_sem (); int main () {pthread_t fa, ma, so, da; sem_init (& remain, 0, total) / / the total number is initialized to 20 sem_init (& apple, 0,0); / / the number of apples in the basin starts with 0 sem_init (& pear, 0,0); / / the number of pears in the basin starts with 0 sem_init (& mutex, 0,1); / / the mutex starts with 1 pthread_create (& fa, NULL, & father, NULL); pthread_create (& ma, NULL, & mather, NULL) Pthread_create (& so, NULL, & son, NULL); pthread_create (& da, NULL, & daughter, NULL); for (;);} void * father (void * arg) {while (1) {sem_wait (& remain); sem_wait (& mutex) Printf ("Father: before putting apples, remaining space =% u, number of apples =% u\ n", vremain--, vapple++); printf ("Father: after putting apples, remaining space =% u, number of apples =% u\ n", vremain, vapple); sem_post (& mutex); sem_post (& apple); sleep (1) } void * mather (void * arg) {while (1) {sem_wait (& remain); sem_wait (& mutex); printf ("Mother: before putting pears, remaining space =% u, number of pears =% u\ n", vremain--, vpear++) Printf ("Mother: after putting pears, remaining space =% u, number of pears =% u\ n", vremain, vpear); sem_post (& mutex); sem_post (& pear); sleep (2);}} void * son (void * arg) {while (1) {sem_wait (& pear) Sem_wait (& mutex); printf ("son: before eating pears, remaining space =% u, number of pears =% u\ n", vremain++, vpear--); printf ("son: after eating pears, remaining space =% u, number of pears =% u\ n", vremain, vpear); sem_post (& mutex); sem_post (& remain) Sleep (3);}} void * daughter (void * arg) {while (1) {sem_wait (& apple); sem_wait (& mutex); printf ("daughter: before eating apples, remaining space =% u, number of apples =% u\ n", vremain++, vapple--) Printf ("daughter: before eating apples, remaining space =% u, number of apples =% u\ n", vremain, vapple); sem_post (& mutex); sem_post (& remain); sleep (3);}} void print_sem () {int val1, val2, val3; sem_getvalue (& remain, & val1) Sem_getvalue (& apple, & val2); sem_getvalue (& pear, & val3); printf ("Semaphore: remain:%d, apple:%d, pear:%d\ n", val1, val2, val3);} remember to add-lpthread when compiling otherwise sem_ is undefined.
Because there is an endless loop in the main function, the program will keep running.
Thank you for reading! This is the end of this article on "what is semaphore in Linux?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.