2

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!

Chris Watts
  • 6,197
  • 7
  • 49
  • 98

1 Answers1

5

std::async returns a future which wait on destruction, you have to use a member for it or use std::thread directly (detached).

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Very interesting! I did see something about the destructor argument but never linked it with not storing the `future` in a variable – Chris Watts Sep 15 '15 at 17:28