Last active
August 26, 2025 13:03
-
-
Save 27Cobalter/21e66c8ac3950e4d7cf7eb0e0be4c4a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <chrono> | |
| #include <condition_variable> | |
| #include <cstdint> | |
| #include <iostream> | |
| #include <mutex> | |
| #include <stop_token> | |
| #include <thread> | |
| auto main() -> int32_t { | |
| std::mutex mut; | |
| std::condition_variable cond; | |
| std::stop_source source; | |
| std::thread th([&mut, &cond, &source]() { | |
| std::cout << "child start" << std::endl; | |
| auto token = source.get_token(); | |
| { | |
| std::cout << "child try lock" << std::endl; | |
| std::unique_lock<std::mutex> lock(mut); | |
| std::cout << "child locked" << std::endl; | |
| cond.wait(lock, [&token]() { | |
| bool requested = token.stop_requested(); | |
| std::cout << "child check request: " << requested << std::endl; | |
| std::this_thread::sleep_for(std::chrono::seconds(3)); | |
| std::cout << "child sleep" << std::endl; | |
| return requested; | |
| }); | |
| std::cout << "child wakeup" << std::endl; | |
| } | |
| }); | |
| std::this_thread::sleep_for(std::chrono::seconds(2)); | |
| { | |
| std::cout << "parent try lock" << std::endl; | |
| // std::lock_guard<std::mutex> lock(mut); | |
| std::cout << "parent locked" << std::endl; | |
| source.request_stop(); | |
| std::cout << "parent send stop" << std::endl; | |
| } | |
| cond.notify_all(); | |
| std::cout << "parent send notify" << std::endl; | |
| th.join(); | |
| std::cout << "parent join success" << std::endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment