Semaphore (semaphore) based on multi-threaded concurrency-STL

1. The difference between the semaphores provided by the operating system

1. The difference between the semaphores provided by the operating system
2. The semaphores provided by c++20 can only be used for thread synchronization between the same process

Two, c++20 semaphore

A semaphore is a lightweight synchronization primitive used to restrict concurrent access to shared resources. Semaphores can be more efficient than condition variables when both can be used.

project Value
counting_semaphore(C++20) counting_semaphore(C++20)
binary_semaphore(C++20) binary_semaphore(C++20)

1. Environment configuration:
a. Defined in the header file
b. Visual studio is upgraded to 2019
c. Turn on the switch of c++20 support

2. Example of use

#include <iostream>
#include <semaphore>
#include <thread>
using namespace std;

std::counting_semaphore<3> csem(0);

binary_semaphore bsem(0);

// semaphore release = condition_variable notify
// semaphore acquire = condition_variable wait
void task()
{
    
    
    cout << "task:ready to recv signal \n";
    csem.acquire();
    cout << "task:acquire end\n";
}
int main()
{
    
    
    thread t0(task);
    thread t1(task);
    thread t2(task);
    thread t3(task);
    thread t4(task);

    cout << "main:ready to signal :release\n";
    csem.release(3);
    cout << "main: signal end\n";

    t0.join();
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

If there are any mistakes or deficiencies, welcome to comment and point out! Creation is not easy, please indicate the source for reprinting. If it is helpful, remember to like and follow (⊙o⊙)
For more content, please follow my personal blog: https://blog.csdn.net/qq_43148810

Guess you like

Origin blog.csdn.net/qq_43148810/article/details/130646633