下面是一个例子,编译通过。
#include <future>
#include <functional>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
class Msg {
public:
Msg(std::string name, uint32_t id) : m_name(name), m_id(id)
{
}
virtual ~Msg()
{
}
std::string GetName()
{
return m_name;
}
uint32_t GetId()
{
return m_id;
}
private:
std::string m_name;
uint32_t m_id;
};
void PrintInfo(Msg *msg)
{
for (int i = 0; i < 10; i++) {
std::cout << msg->GetName() << msg->GetId() << std::endl;
}
}
// function object point to the method.
std::function<void(Msg *msg)> printFunc = PrintInfo;
int main()
{
Msg *msg = new Msg("Hello", 999);
std::future<void> fut = std::async(std::launch::async, PrintInfo, msg);
Msg *msg2 = new Msg("World", 123);
std::future<void> fut2 = std::async(std::launch::deferred, PrintInfo, msg2);
// independent of platform.
std::this_thread::sleep_for(std::chrono::milliseconds(10000));
fut2.get();
// use lambda
std::future<bool> fut3 = std::async(std::launch::deferred, [](std::string name) -> bool {
if (name == "s") {
std::cout << "start!" << std::endl;
return true;
}
return false;
}, "s");
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
fut3.get();
// use function.
std::future<void> fut4 = std::async(std::launch::deferred, printFunc, new Msg("Function Msg", 777));
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
fut4.get();
return 0;
}
编译时记得要加上-lpthread
g++ -o test_future test_future -lpthread
输出结果
Hello999
Hello999
Hello999
Hello999
Hello999
Hello999
Hello999
Hello999
Hello999
Hello999
World123
World123
World123
World123
World123
World123
World123
World123
World123
World123
start!
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777
Function Msg777