C++20: semaphores

There are two types of semaphores:

  • std::binary_semaphore
  • std::counting_semaphore

Semaphore alllows multiple access to shared resources. Unlike std::mutex, semaphore can be locked in one thread, and unlocked in another.


std::binary_semaphore is just alias for std::counting_semaphore.

using binary_semaphore = std::counting_semaphore<1>;


Semaphore has in implementation counter, which defines, how many threads can enter to locked section.

For example:

std::counting_semaphore<3> sem{ 0 };

In this case, maximum counter values can be 3. And counter is initialized to 0.

acquire() – decrements value, and if counter is already 0, will block until counter is larger than 0.

release() – increments counter

For example:

#include <iostream>

#include <thread>

#include <semaphore>

std::counting_semaphore<1> sem{ 0 };

void thread_func1()



std::cout << "analyze data()" << std::endl;


void thread_func2()


std::cout << "getting data()" << std::endl;



int main()


std::jthread thread1{ thread_func1 };

std::jthread thread2{ thread_func2 };


In this case, first we need to wait for data in first thread.

Leave a Reply

Your email address will not be published.