// global binary semaphore instances// object counts are set to zero// objects are in non-signaled statesmphSignalMainToThread:std::binary_semaphore=(0);smphSignalThreadToMain:std::binary_semaphore=(0);ThreadProc:()={// wait for a signal from the main proc// by attempting to decrement the semaphoresmphSignalMainToThread.acquire();// this call blocks until the semaphore's count// is increased from the main procstd::cout<<"[thread] Got the signal\n";// response message// wait for 3 seconds to imitate some work// being done by the threadusingstd::literals::_;std::this_thread::sleep_for(3s);std::cout<<"[thread] Send the signal\n";// message// signal the main proc backsmphSignalThreadToMain.release();}main:()={// create some worker threadthrWorker:std::thread=(ThreadProc);std::cout<<"[main] Send the signal\n";// message// signal the worker thread to start working// by increasing the semaphore's countsmphSignalMainToThread.release();// wait until the worker thread is done doing the work// by attempting to decrement the semaphore's countsmphSignalThreadToMain.acquire();std::cout<<"[main] Got the signal\n";// response messagethrWorker.join();}
Output
[main] Send the signal
[thread] Got the signal
[thread] Send the signal
[main] Got the signal