====== C - C++ Asynchronous function call ======
===== futuresample.hpp =====
#pragma once
#include
// Call a function in another thread, using a std::future.
std::wstring use_future(std::string filename);
----
===== future_sample.cpp =====
#include "futuresample.hpp"
#include
#include
#include
class SampleReadClass
{
public:
static std::wstring staticfunction_read(std::string filename)
{
std::wostringstream stream;
stream << std::wifstream(filename).rdbuf();
return stream.str();
}
std::wstring memberfunction_read(std::string filename)
{
return staticfunction_read(filename);
}
};
std::wstring use_future(std::string filename)
{
// Sample 1.
std::future f1 = std::async(SampleReadClass::staticfunction_read, filename);
// Sample 2.
SampleReadClass sampleReadClass;
std::future f2 = std::async([&]
{
return sampleReadClass.memberfunction_read(filename);
});
//
// Do other things here...
//
return f1.get() + f2.get();
}
----
===== References =====
https://en.cppreference.com/w/cpp/thread/future