* Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
#include <chrono>
int main()
{
std::atomic<bool> ready(false);
auto worker_thread_func = [&ready]() {
bool expected = false;
bool desired = true;
while (!ready.compare_exchange_strong(expected, desired)) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
expected = false;
}
std::cout << "Worker thread: Ready is now true." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Worker thread: Work completed." << std::endl;
};
std::thread worker(worker_thread_func);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Main thread: Performing setup..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Main thread: Setup complete." << std::endl;
bool expected_main = false;
bool desired_main = true;
ready.compare_exchange_strong(expected_main, desired_main);
std::cout << "Main thread: Signaled worker thread." << std::endl;
worker.join();
std::cout << "Main thread: Worker thread finished." << std::endl;
return 0;
}