Linux Learning Notes (15)-semaphores

Source: Internet
Author: User
Tags function prototype semaphore

In multi-threaded or multi-process programming, there is a very important thing to focus on, that is, synchronization and mutual exclusion problems.

Synchronization refers to the collaboration between multiple processes, whereas mutual exclusion refers to the competition between multiple processes in order to compete for limited resources.

Theory is very high-end, but after a few days of learning, found in the operating system, the thread of the semaphore is relatively simple to understand ...

————————————————————————————————————————

Semaphores are a mechanism for resolving synchronization or mutual exclusion between threads, and a special variable that represents the resources currently available.

If it equals 0, that means no resources are available at this time.

Depending on the value of the semaphore, the semaphore can be divided into two-value semaphores and counting signals:

  (count semaphore) like a public toilet with a total of 10 pits (max 32767), which is 10 resources. At the same time can accommodate 10 people, when full, the outside people must wait for the inside of the people out, release a resource, and then in a, when he went in, the toilet is full, the outside people have to continue to wait ...

  (binary semaphore) just like your own bathroom, there is usually only one toilet, at the same time only one person to use.

Semaphores can only process two atomic operations, p operation and V operation,

  Concept:

Atomic operations, which cannot be interrupted by higher levels, take precedence over operations.

Because the operating system is in an interrupt state most of the time, a program may be interrupted by a higher priority thread when it executes.

And some operations can not be interrupted, or there will be an inability to restore the consequences, at this time, these operations require atomic operation. is an operation that cannot be interrupted.

  P Operation: if there are available resources (semaphore >0), then occupy a resource (semaphore-1). If no resources are available (semaphore =0), the process is blocked until the system assigns him resources again.

  v Operation: If there is a process waiting for the resource in the wait queue for that semaphore, a process is awakened, or a resource is freed (semaphore + 1)

  

POSIX provides two types of semaphores, known semaphores and nameless semaphores , and known semaphores are typically used to synchronize between processes, and nameless semaphores are generally synchronized between threads.

The operation flow of the two signals is probably different from the following points:

  

Mainly in the two types of signal initialization and destruction of different ways.

  By the way, there is a great need to be aware of, and in the operation of shared memory requires a connection library, when compiling the semaphore, you also need to add the -pthread parameter .

————————————————————————————————————————————————————————————

  First, learn the famous semaphore.

 Create a named semaphore:

To create or open a semaphore, you need to use the Sem_open () function, which is as follows:

sem_t Sem_open (const char * name, int oflag, mode_t mode, unsigned int value)

The return value sem_t is a struct, and if the function call succeeds, it returns a pointer to the structure containing the current semaphore's number of resources.

The parameter name is the name of the semaphore, and two different processes pass through the same name to signal the volume.

Parameter Oflag, when he is o_creat, if the semaphore given by name does not exist, then the mode and Vaule must be given at this time. When he was a o_excl, there seemed to be no significant significance.

The parameter mode, which is well understood, is used to specify the semaphore's permissions.

The Vaule parameter is the initial value of the semaphore.

 To turn off a known semaphore:

The function used to close the known semaphore is Sem_close (sem_t *sem)

This function has only one parameter, meaning is very obvious, that is, the name of the semaphore.

  

  Semaphore Operation:

As already mentioned, there are two very important operations when using semaphores

P Operation: The function used is sem_wait (sem_t *sem)

If the semaphore value is greater than 0, the sem_wait function will decrement the semaphore by one and return immediately. If the semaphore value is less than 0, then the process will be blocked in place.

V Operation: The function used is sem_post (sem_t *sem)

When a process finishes using a semaphore, he should call the Sem_post function to tell the system to reclaim the resource.

The Sem_post function and the sem_wait function are exactly the opposite, and he will add a specified amount of semaphore

  To delete a named semaphore:

When a known signal is used, the function Sem_unlink needs to be called to release the resource.

Function prototype: int sem_unlink (const char *name)

——————————————————————————————————————————————————————————

  Practical Walkthrough!!!

Requirements: Create two processes, a process to print a, and then wait for B process to print B, after the B process has finished printing, a process is printing C.

A process code is as follows:

  

#include <stdio.h>#include<stdlib.h>#include<semaphore.h>#include<errno.h>#include<sys/stat.h>#include<fcntl.h>#defineSem_name "NAME"intMain () {sem_t*sem_test;sem_test= Sem_open ("ni", O_creat,0644,0); if(Sem_test <0) {printf ("a process creation semaphore failed! errno=%d\n", errno); Exit (-1); } printf ("process a enters wait ... \ n"); printf ("a\n");    Sem_wait (sem_test); printf ("c\n");    Sem_post (sem_test); printf ("a Process execution is complete! \ n");

Sem_close (sem_test);
Sem_unlink ("ni");

return 0;
}

The B process code is as follows:

  

#include <stdio.h>#include<stdlib.h>#include<semaphore.h>#include<errno.h>#include<sys/stat.h>#include<fcntl.h>#defineSem_name "NAME"intMain () {sem_t*sem_test;sem_test= Sem_open ("ni",0); if(Sem_test <0) {printf ("b process failed to create semaphore! errno=%d\n", errno); Exit (-1); } printf ("b\n");    Sem_post (sem_test); printf ("b Process Execution finished! \ n");    Sem_close (sem_test); Sem_unlink ("ni"); return 0;}

Now the process compiles (be sure to remember to add-pthread after the compile option!! )

   

Code Execution Results!!

   

The execution was very successful!!

It is worth mentioning that if there is a segment error (Core dump) in the execution of this error message, it is best to go to /dev/shm/ under the check to see if there is a yellow file, permissions are set to the odd high!

I was confronted with such a problem.

Hey! Although the whole article is so short of dozens of lines, but I have struggled for nearly five hours to understand!!

Tomorrow ~ Continue to refuel!!

  

       

  

  

  

  

  

  

Linux Learning Notes (15)-semaphores

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.