Communication learning between Linux processes: how to use semaphores

Source: Internet
Author: User
Tags resource semaphore thread

This article will describe the mechanism of communication between processes-semaphores. Please do not confuse it with the signal previously mentioned, signal and signal volume are two different things. For more information about the signal, you can read my other article: Linux interprocess Communication--using signals. The following is the explanation of the signal quantity.

One, what is the signal quantity

In order to prevent a series of problems caused by multiple programs accessing a shared resource at the same time, we need a way to authorize the generation and use of tokens to have only one critical area in which to execute thread access code at any one time. A critical area is a code that performs a data update that needs to be executed in an exclusive manner. The semaphore can provide such an access mechanism that only one thread in a critical section accesses it at the same time, that is, the semaphore is used to co-ordination process access to shared resources.

A semaphore is a special variable whose access to the program is atomic, and only allows it to wait (i.e. p (signal variable)) and send (i.e. V (signal variable)) information operations. The simplest semaphore is a variable that can only take 0 and 1, which is also the most common form of semaphore, called the binary semaphore. The number of signals that can take multiple positive integers is called the universal semaphore. Here we mainly discuss the binary signal quantity.

The working principle of signal quantity

Because semaphores can only perform two kinds of operation waiting and sending signals, i.e. P (SV) and V (SV), they behave like this:

P (SV): If the value of the SV is greater than 0, it is reduced by 1; If its value is zero, the execution of the process is suspended

V (SV): If there are other processes that are suspended for the SV, let it resume and add 1 if no process hangs because it waits for the SV.

For example, two processes share the semaphore SV, and once one of the processes performs the P (SV) operation, it will get the semaphore and enter the critical section to reduce the SV by 1. The second process is blocked from entering the critical section, because when it attempts to execute the P (SV), the SV is 0 and it is suspended to wait for the first process to leave the critical area and perform the V (SV) Release semaphore, when the second process can resume execution.

Third, the Linux signal volume mechanism

Linux provides a well-designed set of semaphore interfaces to manipulate signals, not just binary semaphores, which are described below, but note that these functions are used to manipulate the set of semaphore values in a group of variables. They are declared in the header file sys/sem.h.

1. Semget function

Its role is to create a new semaphore or to obtain an existing semaphore, the prototype is:

int Semget (key_t key, int num_sems, int sem_flags);

The first parameter key is an integer value (only 0), and the unrelated process can access a semaphore through it, which represents a resource that the program might want to use, and the program's access to all semaphores is indirect, and the program first calls the Semget function and provides a key, A corresponding signal identifier (the return value of the Semget function) is generated by the system, and only the Semget function uses the semaphore key directly, and all other semaphore functions use the semaphore identifier returned by the Semget function. If multiple programs use the same key value, key will be responsible for coordinating the work.

The second parameter num_sems specifies the number of semaphores required, and its value is almost always 1.

The third parameter, Sem_flags, is a set of flags that, when you want to create a new semaphore when the semaphore does not exist, can be bitwise or manipulated with the value ipc_creat. When the IPC_CREAT flag is set, no error occurs even if the given key is a key that already has a semaphore. and Ipc_creat | IPC_EXCL can create a new, unique semaphore that returns an error if the semaphore already exists.

The Semget function successfully returns a corresponding signal identifier (not 0) and the failure returns-1.

2. Semop function

Its function is to change the value of the semaphore, the prototype is:

int semop (int sem_id, struct sembuf *sem_opa, size_t num_sem_ops);

SEM_ID is the semaphore identifier returned by Semget, and the SEMBUF structure 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 needs to be changed in one operation, usually two digits, one is-1, the P (wait) operation,  
                    //One is +1, that is V (send signal) operation. The short  
    sem_flg;//is usually sem_undo, allowing the operating system to track the signal,  
                    //and the operating system to release the semaphore if the signal is not released by the process  
;

3. Semctl function

This function is used to directly control semaphore information, and its prototype is:

int semctl (int sem_id, int sem_num, int command, ...);

If there is a fourth argument, it is usually a union semum structure, defined as follows:

Union semun{  
    int val;  
    struct Semid_ds *buf;  
    unsigned short *arry;  
};

The first two parameters are the same as in the previous function, and the command is usually one of the following two values

Setval: Used to initialize the semaphore to a known value. P This value is set by the Val member in Union Semun, and its effect is to set the semaphore before it is used for the first time.

Ipc_rmid: Used to delete a semaphore identifier that no longer has to be used.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.