C++20에 드디어 세마포어가 도입되어서 WINAPI 정복에서 쓰였던 샘플 코드를 짜 보기로 함

C++20에는 counting_semaphore과 binary_semaphore가 있는데, counting_semaphore는 실행 가능한 쓰레드 개수를 정할 수 있는 세마포어고 binary_semaphore는 실행 가능 개수가 1인 counting_semaphore임


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36#include <iostream> #include <thread> #include <semaphore> #include <chrono> #include <syncstream> #include "random.hpp" using Random = effolkronium::random_thread_local; using namespace std; counting_semaphore<3> sm{ 3 }; void calcu(int num, int to) { sm.acquire(); osyncstream(cout) << num << " waited" << endl; for (int i = 0; i <= to; i++) { auto k = Random::get(1, 500); osyncstream(cout) << "thread: " << num << " now: " << i << " sleep : " << k << endl; } osyncstream(cout) << num << " finished" << endl; sm.release(); } int main() { vector<thread> threads; for (int i = 0; i < 10; i++) { threads.push_back(thread(calcu, i, 3)); } for (int i = 0; i < 10; i++) { threads[i].join(); } }



실행 결과




세마포어에서 정의된 데로 3개의 쓰레드만 동시에 실행되는 것을 볼 수 있음