即使调用了 get() ,未来也不是 运行

future is not run even if get() is called

我想 运行 一些 system 并行调用,但即使我调用 f1.get() 下面几行中的应对也不会发生。这段代码有什么问题?

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

注意:我写 string(...).c_str() 是因为在我的实际代码中,我使用的是将来自不同字符串的参数放在一起。

包含您的命令的 std::string 是一个临时对象,只会在 std::async 调用结束之前存在, 所以当 system 被调用时,指针可能指向已删除的内存,这可能恰好起作用,或者它可能读取 rm -rf / --no-preserve-root - 这是未定义的行为。

您需要确保字符串对象的寿命足够长。在您的示例中,这很简单,但如果您启动异步操作,则并非总是如此。

C++11 lambda 表达式为我们提供了一种很好的方式来存储字符串,只要我们需要它就可以:

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()); 
    }
);

另外请注意,您没有请求 async 启动策略,因此您的函数可能仍会同步执行。

旁注:如果您要启动外部进程并希望捕获输出、退出状态等,您可能需要考虑使用 POCO's Process 之类的东西。