Linux system programming semaphore


As we all know, mutexes can be used for synchronization between threads. However, only one thread can seize the mutex at a time, which limits the release of programs. If we want to allow multiple threads to access the same resource at the same time, there is no way to use mutex. Only mutex will lock the whole shared resource and allow only one thread to access it.

This phenomenon makes the thread run in turn, that is, the thread from parallel execution to serial execution, which is the same as using single process directly.

Therefore, Linux system puts forward the concept of semaphore. It can not only ensure the synchronization between threads, but also improve the concurrency of threads. Note that the semaphores mentioned here have nothing to do with the semaphores we learned, just as Java has nothing to do with JavaScript.

Main application functions:

​ sem_ Init function
​ sem_ Destroy function
​ sem_ Wait function
​ sem_ Trywait function
​ sem_ Timedwait function
​ sem_ Post function
The return values of the above six functions are: success returns 0, failure returns – 1, and sets errno.

Careful readers may notice that they have no pthread prefix, which means semaphores can be used not only between threads, but also between processes.

sem_ The essence of T data type is still structure. But like file descriptors, we can simply treat them as integers during application, ignoring implementation details.

Usage: SEM_ We agree that semaphore SEM cannot be less than 0. When using, note that the header file < semaphore. H > is included.

Similar to mutex lock, semaphore also has similar lock and unlock operations, lock using SEM_ Wait function, unlock using SEM_ Post function. These two functions have the following characteristics:

  1. Calling SEM_ In post, if the semaphore is greater than 0, the semaphore is subtracted by one;
  2. When the semaphore is equal to 0, SEM is called_ Post will cause thread blocking;
  3. Calling SEM_ When post, the semaphore is increased by one, and the thread blocked on the semaphore is awakened.

The operation of adding one minus one to the thread mentioned above is due to SEM_ The implementation of T is hidden from users, so these two operations can only be implemented by functions, not directly using the + + and — symbols.

sem_ Init function

Function prototype:
int sem_init(sem_t *sem, int pshared, unsigned int value);

Function function:
Initialize a semaphore;

Parameter Description:
sem: semaphore;
pshared: when 0 is selected, semaphore is used for inter thread synchronization; when non-0 (generally 1), it is used for inter process synchronization;
value: Specifies the initial value of the semaphore, which determines the number of threads allowed to occupy the semaphore at the same time.

sem_ Destroy function

Function prototype:
int sem_destroy(sem_t *sem);

Function function:
Destroy a semaphore

sem_ Wait function

Function prototype:
int sem_wait(sem_t *sem);

Function function:
Add one to the semaphore

sem_ Post function

Function prototype:
int sem_post(sem_t *sem);

Function function:
Subtract one from the semaphore

sem_ Trywait function

Function prototype:
int sem_trywait(sem_t *sem);

Function function:
Try to lock the semaphore, and pthread_ mutex_ Trylock was similar;

sem_ Timedwait function

Function prototype:
int sem_timedwait(sem_t sem, const struct timespec abs_timeout);

Function function:
Try to lock the semaphore in limited time

Parameter Description:
sem: semaphore;
abs_timeout: and pthread_ cond_ Just like timedwait, absolute time is used.

The usage is as follows (for example, the timeout is set to 1 second)

time_ T cur = time (null); gets the current time.
Struct timespec T; define timespec structure variable t
t.tv_ SEC = cur + 1; timing 1 second
t.tv_nsec = t.tv_sec +100;
sem_ Timedwait & SEM, & T; transfer parameters

Producer consumer semaphore model

/*Semaphore realizes producer consumer problem*/

#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>

#define NUM 5               

Int queue [num]; // global array implements ring queue
sem_ t blank_ number, product_ Number; // empty cell semaphore, product semaphore

void *producer(void *arg)
    int i = 0;

    while (1) {
        sem_ wait(&blank_ Number); // the producer will block the waiting if it is 0
        Queue [i] = rand()% 1000 + 1; // produce a product
        printf("----Produce---%d\n", queue[i]);        
        sem_ post(&product_ Number); // number of products++

        I = (I + 1)% num; // ring with subscript

void *consumer(void *arg)
    int i = 0;

    while (1) {
        sem_ wait(&product_ Number); // the number of products --, 0 will block waiting
        printf("-Consume---%d\n", queue[i]);
        Queue [i] = 0; // consume a product 
        sem_ post(&blank_ Number); // after consumption, the number of empty cells will be increased++

        i = (i+1) % NUM;

int main(int argc, char *argv[])
    pthread_t pid, cid;

    sem_ init(&blank_ Number, 0, Num); // initialize the empty cell semaphore to 5
    sem_ init(&product_ Number, 0, 0); // the number of products is 0

    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);

    pthread_join(pid, NULL);
    pthread_join(cid, NULL);


    return 0;

Operation results:

Linux system programming semaphore

More interesting content, please pay attention to the official account.Liang Xu Linux, public response10245T technical data can be obtained free of charge, including:Linux, C / C + +, python, raspberry pie, embedded, Java, artificial intelligence, etc. Reply in official accountEntering a group, invite you to join the cloud technology exchange group.

Finally, a lot of friends have come to me recentlyLinux learning RoadmapBased on my own experience, I used my spare time to stay up late for a month and sorted out an e-book. Whether you are interview or self-improvement, I believe it will help you!

Free to everyone, just ask you to give me a compliment!

E-book | Linux development learning Roadmap

Also hope to have a small partner to join me, make this e-book more perfect!

What’s the gain? I hope the old fellow will take three strikes to show this article to more people.

Recommended reading: