dani
dani

Reputation: 3887

future is not run even if get() is called

I want to run some system calls in parallel, but even if I call f1.get() the coping in the lines below does not take place. What is wrong with this code?

auto f1 = std::async( system, string("cp a b").c_str() );
f1.get(); // there is still no file "b".

Note: I wrote string(...).c_str() because in my real code I'm using putting the argument together from different strings.

Upvotes: 1

Views: 100

Answers (1)

melak47
melak47

Reputation: 4850

The std::string containing your command is a temporary object and will only live until the end of the std::async call, so by the time system is called, the pointer may refer to deleted memory, which may happen to work, or it might read rm -rf / --no-preserve-root - it's undefined behavior.

You need to ensure the string object lives long enough. In your example that is easy enough, but it's not always so if you're launching asynchronous operations.

C++11 lambda expressions give us a nice way store the string for exactly as long as we need it:

std::string command = "cp main.cpp b";

auto f1 = std::async(std::launch::async, 
    [command]{ // copy command into the closure
        std::system(command.c_str()); 
    }
);

Also, note that you didn't request the async launch policy, so your function may execute synchronously still.

Side note: You may want to consider using something like POCO's Process if you're launching external processes and want to capture output, exit status and so on.

Upvotes: 2

Related Questions