Linux system Programming-thread synchronization and mutual exclusion: nameless semaphores

Source: Internet
Author: User
Tags semaphore

Signal Volume Overview

Semaphores are widely used for synchronization and mutual exclusion between processes or threads, which is essentially a nonnegative integer counter that is used to control access to public resources.


programming can be based on the results of the operation of the semaphore value to determine whether the public resources have access permissions, when the semaphore value is greater than 0 o'clock, you can access, otherwise it will block. The PV primitive is the operation of the semaphore, a P operation to reduce the signal volume by 1, and a V operation to increase the signal volume by 1.


Semaphores are primarily used for synchronization and mutual exclusion between processes or threads.

The semaphore is used for mutual exclusion:



The semaphore is used for synchronization:



In the POSIX standard, the semaphore is divided into two types, one is the nameless semaphore, and the other is a well-known semaphore. The nameless semaphore is typically used for inter-thread synchronization or mutual exclusion, and a well-known semaphore is typically used for inter-process synchronization or mutual exclusion. Their differences are similar to pipes and named Pipes, where the nameless semaphore is stored directly in memory, and a well-known semaphore requires a file to be created.


unknown Semaphore basic Operation

The following function requires the header file:

#include <semaphore.h>


Note : When compiling semaphore manipulation functions, you need to add the parameter -lpthread.


The semaphore data type is:sem_t.


1) Initialization of the semaphore

int Sem_init (sem_t *sem, int pshared, unsigned int value);

Function:

Creates a semaphore and initializes its value. A nameless semaphore must be initialized before it can be used.

Parameters:

sem: The address of the semaphore.

pshared: equals 0, semaphores are shared between threads ( common ), not equal to 0, and semaphores are shared among processes.

value: The initial value of the semaphore.

return value:

Success: 0

Failed:-1


2) Signal Volume P operation (minus 1)

int sem_wait (sem_t *sem);

Function:

Reduce the value of the semaphore by 1. Before operation, check whether the value of the semaphore (SEM) is 0, if the semaphore is 0, this function will block until the semaphore is greater than 0 o'clock minus 1 operation.

Parameters:

sem : The address of the semaphore.

return value:

Success: 0

Failed:-1


int sem_trywait (sem_t *sem);

A non-blocking way to reduce the semaphore by 1 operation. If the value of the semaphore is equal to 0 before the operation, the operation of the semaphore fails and the function returns immediately.


3) Signal Volume V operation (plus 1)

int Sem_post (sem_t *sem);

Function:

Adds 1 to the semaphore and signals the wake-up Waiting Thread (sem_wait ()).

Parameters:

sem : The address of the semaphore.

return value:

Success: 0

Failed:-1


4) Get the value of the semaphore

int Sem_getvalue (sem_t *sem, int *sval);

Function:

Gets the value of the semaphore identified by the SEM, stored in the sval.

Parameters:

sem: semaphore address.
Sval: The address where the semaphore value is saved.

return value:

Success: 0

Failed:-1


5) Destroy the semaphore

int Sem_destroy (sem_t *sem);

Function:

Remove the semaphore identified by the SEM.

Parameters:

sem: semaphore address.

return value:

Success: 0

Failed:-1


Unknown Semaphore application Example

The semaphore is used for mutually exclusive instances:

#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h>sem_t sem; semaphore void Printer (char *str) {sem_wait (&SEM);//Minus one while (*STR) {Putchar (*STR); fflush (stdout); Str++;sleep (1);} printf ("\ n"); Sem_post (&sem);//Add a}void *thread_fun1 (void *arg) {char *str1 = "Hello";p rinter (STR1);} void *thread_fun2 (void *arg) {char *str2 = "World";p rinter (STR2);} int main (void) {pthread_t tid1, tid2;sem_init (&sem, 0, 1);//Initialize semaphore, initial value 1//create 2 threads pthread_create (&tid1, NULL, th READ_FUN1, NULL);p thread_create (&tid2, NULL, thread_fun2, NULL);//wait for thread to end, reclaim its resources pthread_join (TID1, null);p Thread_ Join (TID2, NULL); Sem_destroy (&sem); Destroy Semaphore return 0;}

The results of the operation are as follows:



The semaphore is used to synchronize the instance:

#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h>sem_t sem_g, sem_p;   Define two semaphores char ch = ' a '; void *pthread_g (void *arg)  //This thread alters the value of the character ch {while (1) {sem_wait (&sem_g); Ch++;sleep (1); SEM _post (&sem_p);}} void *pthread_p (void *arg)  //This thread prints the value of CH {while (1) {sem_wait (&sem_p);p rintf ("%c", ch); fflush (stdout); sem_post (&sem_g);}} int main (int argc, char *argv[]) {pthread_t tid1,tid2;sem_init (&sem_g, 0, 0);   Initialize Semaphore sem_init (&sem_p, 0, 1);p thread_create (&TID1, NULL, PTHREAD_G, NULL);p thread_create (&TID2, NULL, Pthread_p, NULL);p thread_join (TID1, NULL);p thread_join (TID2, null); return 0;}

The results of the operation are as follows:


For this tutorial sample code download please click here.

Linux system Programming-thread synchronization and mutual exclusion: nameless 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.