Linux Posix Semaphore Volume Two

Source: Internet
Author: User
Tags mutex posix semaphore

One, POSIX signal volume

The 1.Posix semaphore is divided into two types:

1. Known semaphores: Using POSIX IPC name identifiers (known semaphores are always available for synchronization between threads and for inter-process synchronization)

2. Memory semaphore: stored in the shared memory area (memory-based semaphores must be specified at creation time to be shared between processes, and in the shared memory area of all processes, with ongoing process persistence)

The POSIX semaphore does not have to be maintained in the kernel (the System v Semaphore is maintained by the kernel) and is identified by the name that may be the path name.

(POSIX semaphores are more commonly used for inter-process synchronization, and mutexes are often used for inter-thread synchronization)

2. Basic Operation:

1. Create: Specify the initial value.

2. Wait: If the value is less than or equal to 0 is blocked, otherwise it is reduced by one, also called P operation.

3. Hang out (POST): Add the value of the semaphore to 1, plus if the value is greater than 0, wake up a thread that is blocking on the wait, also known as the V operation.

A binary semaphore can be used for mutual exclusion, just like a mutex. But the mutex must be threads unlocked by the line that locks it, and the semaphore is hung without having to be executed by the same thread that performed the wait.

The wait and post of the semaphore are similar to the wait and signal of the condition variable, except that the operation of the semaphore is always remembered (which affects subsequent operations) because it permanently alters the value of the semaphore; the signal of the condition variable if no thread is waiting, The signal will be lost (no effect on subsequent operations).

The mutex is optimized for locking, the condition variable is waiting for optimization, the semaphore can be locked and wait, so the overhead is greater.

3.Posix Semaphore operation

Known signal volume:

Memory Signal Volume:


Sem_init: You need to specify whether to share

Sem_wait: Atomic "Test and minus 1" operation


Sem_post: The only operation in the synchronization technique that can be safely invoked within a signal processing function





Even if no process is currently opening the semaphore, its value remains, so POSIX-known semaphores are at least persistent with the kernel.

Any semaphore that is opened in the parent process and is still open in the child process after the fork.

Some notes on the use of POSIX-known semaphores :

1. A well-known semaphore is removed from the system using Sem_unlink. Each semaphore has a reference counter that records the current number of open times, and Sem_unlink must wait for this number to be 0 o'clock to remove the semaphore that is referred to by name from the file system. That is to wait for the last sem_close to happen.

2. When a semaphore is used between processes that are not related to each other, a known semaphore is commonly used. If you do not need to use the associated name, you can use memory semaphores instead.

The memory semaphore needs to be placed in the shared memory area and initialized by the Sem_init function to a shared state to be used by different processes, in which case the persistence is the same as the shared memory area. Sem_init always initializes the value of the semaphore, so for a given semaphore, care must be taken to ensure that only sem_init is called once.

3, we can use sem_wait to apply for shared resources, the SEM_WAIT function can test the value of the specified semaphore, if the value is greater than 0, then subtract it by 1 and return immediately. We'll be able to use the shared resources we've requested. If the value equals 0, the calling thread goes to sleep until the value becomes greater than 0, and then it is reduced by 1, and the function then returns. The sem_wait operation must be atomic. The difference between sem_wait and sem_trywait is that when the value of the specified semaphore is already 0 o'clock, the latter does not put the calling thread to sleep. Instead, it returns a Eagain error.

When a thread finishes using a semaphore, it should call Sem_post to tell the system that the requested resource is exhausted. This function, in contrast to the sem_wait function, adds 1 to the value of the specified semaphore, and then wakes up any thread that is waiting for the semaphore value to become a positive number.

4,. The value of the POSIX-known semaphore is persisted with the kernel. That is, a process creates a semaphore, and after the process is over, the semaphore still exists, and the value of the semaphore does not change.

5. When a process holding a semaphore lock does not release it, the kernel does not unlock the semaphore.

POSIX-known semaphores applied to multithreading

#include <semaphore.h>

#include <unistd.h>

#include <stdio.h>

#include <fcntl.h>

#include <thread.h>

void *thread_function (void *arg); /* Thread Entry function */

void print (pid_t); /* Shared resource function */

Sem_t *sem; /* Define POSIX-named semaphores */

int Val; /* Define semaphore Current Value */

int main (int argc,char *argv[])


int n=0;

if (argc!=2)


printf ("Please input a file name!\n");

Exit (1);


Sem=sem_open (argv[1],o_creat,0644,3); /* Open a semaphore */

while (n++<5)/* Loop creates 5 sub-threads so that they run synchronously */


if ((Pthread_create (&a_thread,null,thread_function,null))!=0)


Perror ("Thread creation failed");

Exit (1);



Pthread_join (A_thread,null);

Sem_close (Bin_sem);

Sem_unlink (argv[1]);


void *thread_function (void *arg)


Sem_wait (SEM); /* Request Semaphore */

Print (); /* Call Shared code snippet */

Sleep (1);

Sem_post (SEM); /* Release the semaphore */

printf ("I ' m finished,my tid is%d\n", pthread_self ());


void print ()


printf ("I get it,my tid is%d\n", pthread_self ());

Sem_getvalue (Sem,&val);

printf ("Now the value has%d\n", Val);


The program builds 5 threads using a looping method, and then lets them invoke the same threading function thread_function, in which we use semaphores to limit the number of threads accessing the shared resource. Shared resources We use the print function to represent, in real programming, it can be a terminal device (such as a printer) or a piece of meaningful code.

Linux Posix Semaphore Volume Two

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: 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.