I am reading about concurrency and trying to write a couple of small programs to test.
Objective: launch a function waiter() in the background and another function, intruder(), in the foreground. While waiter() sleeps intruder() does its stuff and if it returns before waiter() awakes, waiter() holds up main() until it 'awakes', then waiter() returns and finally main() returns.
Problem: (a) in main() if I declare waiter() first, as I should, it holds up intruder() as well, (b) if I create a std::thread object with waiter(), detach this thread, run intruder() and then thread.join() it throws std::system_error what(): Invalid argument
Code:
#include <iostream>
#include <chrono>
#include <thread>
void waiter()
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(5s);
std::cout << "Waited 5 secs!\n";
};
void intruder(){std::cout << "Cheeky me ;) \n";};
int main()
{
waiter();
// std::thread t(waiter);//throws std::system_error
// t.detach();
intruder();
//t.join();
}
Also can the same objective be met with std::future and std::async? I wrote the following but calling get() on the std::future object returns waiter() immediately before 5 seconds are up and without it intruder() returns and then main() returns before waiter() can:
Code:
#include <iostream>
#include <chrono>
#include <future>
void waiter(){ std::cout << "Waited 5 secs!\n";};
void intruder(){std::cout << "Cheeky me ;) \n";};
int main()
{
std::future<void> f1= std::async(std::launch::deferred, waiter);
f1.wait_for(std::chrono::seconds(5));
intruder();
// f1.get();//returns waiter() immediately;
}
Many thanks