User Tools

Site Tools


c:c_asynchronous_function_call

C - C++ Asynchronous function call

futuresample.hpp

#pragma once
 
#include <string>
 
// Call a function in another thread, using a std::future.
std::wstring use_future(std::string filename);

future_sample.cpp

#include "futuresample.hpp"
#include <sstream>
#include <fstream>
#include <future>
 
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<std::wstring> f1 = std::async(SampleReadClass::staticfunction_read, filename);
 
 
  // Sample 2.
  SampleReadClass sampleReadClass;
  std::future<std::wstring> f2 = std::async([&]
  {
    return sampleReadClass.memberfunction_read(filename);
  });
 
 
  //
  // Do other things here...
  //
 
  return f1.get() + f2.get();
}

References

c/c_asynchronous_function_call.txt · Last modified: 2021/04/28 08:56 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki