I'm trying to use std::async
and std::future
in my application to make a background-working daemon. I seem to be getting behaviour that shows I'm not running asynchronously at all!
I've compiled a small bit of code that demonstrates what isn't working for me:
#include <cstdio>
#include <future>
#include <chrono>
class AsyncTest {
public:
void run() {
printf("Entering run()\n");
std::this_thread::sleep_for(std::chrono::seconds(10));
printf("Exiting run()\n");
}
void start() {
printf("Starting daemon...\n");
std::async(std::launch::async, &AsyncTest::run, this);
printf("Daemon started\n");
}
};
int main(int argc, char *argv[])
{
AsyncTest* test = new AsyncTest();
test->start();
std::this_thread::sleep_for(std::chrono::seconds(15));
return 0;
}
Now it should be quite clear that the desired functionality goes like this:
Starting daemon...
Entering run() <--
Daemon started <-- These two may swap
Exiting run() <------ After 10 seconds
exit() <-- After a further 5 seconds
Here's what actually happens:
Starting daemon...
Entering run()
Exiting run() <-- After 10 seconds
Daemon started
exit() <-- After 15 seconds
I'm running this on a BeagleBone Black with Debian Wheezy which does only have one core - but surely this should work regardless with a scheduling operating system!