working commit
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
|
||||
#include <iostream>
|
||||
#include <semaphore>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
|
||||
void worker(int id, std::binary_semaphore* wait, std::binary_semaphore* sign) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
std::cout << std::format("worker {}: working {}\n", id, i);
|
||||
std::chrono::milliseconds timesleep(1s);
|
||||
std::this_thread::sleep_for(timesleep);
|
||||
if (sign->try_acquire()) {
|
||||
std::cout << std::format("worker {}: break\n", id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
wait->release();
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::binary_semaphore wait(0);
|
||||
std::binary_semaphore sign(0);
|
||||
|
||||
std::thread t1(worker, 1, &wait, &sign);
|
||||
t1.detach();
|
||||
|
||||
std::chrono::milliseconds timesleep(1s);
|
||||
std::this_thread::sleep_for(timesleep);
|
||||
sign.release();
|
||||
std::cout << "main: wait worker\n";
|
||||
wait.acquire();
|
||||
std::cout << "main: worker finished\n";
|
||||
|
||||
std::this_thread::sleep_for(timesleep);
|
||||
|
||||
std::cout << "main: exit\n";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user