Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <atomic>
- #include <iostream>
- #include <future>
- class AsyncFunctionExample
- {
- std::atomic<bool> var_1;
- std::atomic<bool> var_2;
- std::atomic<bool> is_finished;
- std::function<void(AsyncFunctionExample&)> current_function;
- void Function1()
- {
- if(!var_1 && !var_2)
- {
- var_1 = true;
- current_function = &AsyncFunctionExample::Function2;
- }
- else if(var_1 && var_2)
- {
- is_finished = true;
- current_function = nullptr;
- }
- }
- void Function2()
- {
- if(var_1 && !var_2)
- {
- var_2 = true;
- current_function = &AsyncFunctionExample::Function1;
- }
- }
- void Test1()
- {
- // this works
- var_1 = false;
- var_2 = false;
- is_finished = false;
- current_function = &AsyncFunctionExample::Function1;
- while(current_function != nullptr)
- current_function(*this);
- }
- void Test2()
- {
- // this works
- var_1 = false;
- var_2 = false;
- is_finished = false;
- current_function = &AsyncFunctionExample::Function1;
- while(current_function != nullptr)
- {
- const std::future<void> function_future = std::async([&](){current_function(*this); });
- function_future.wait();
- }
- }
- void Test3()
- {
- var_1 = false;
- var_2 = false;
- is_finished = false;
- current_function = &AsyncFunctionExample::Function1;
- while(current_function != nullptr)
- {
- const std::future<void> function_future = std::async(current_function, *this);
- function_future.wait();
- }
- }
- public:
- void Run()
- {
- Test1();
- if(!is_finished)
- std::cerr << "Test 1 fails." << "\r\n";
- else
- std::cerr << "Test 1 succeeds." << "\r\n";
- Test2();
- if(!is_finished)
- std::cerr << "Test 2 fails." << "\r\n";
- else
- std::cerr << "Test 2 succeeds." << "\r\n";
- Test3();
- if(!is_finished)
- std::cerr << "Test 3 fails." << "\r\n";
- else
- std::cerr << "Test 3 succeeds." << "\r\n";
- }
- };
- int main() {
- AsyncFunctionExample afe;
- afe.Run();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement