· 4 years ago · Aug 12, 2021, 01:12 PM
1#define BOOST_THREAD_PROVIDES_FUTURE
2#define BOOST_THREAD_PROVIDES_FUTURE_CONTINUATION
3#include <boost/fiber/future/future.hpp>
4#include <boost/fiber/future/async.hpp>
5#include <boost/thread.hpp>
6#include <iostream>
7#include <vector>
8#include <unordered_map>
9#include <string>
10#include <memory>
11
12/////////////////////////////////////////////////////////////////
13// Helpers
14struct PairHash
15{
16 template <class T1, class T2>
17 std::size_t operator() (const std::pair<T1, T2> &pair) const {
18 return std::hash<T1>()(pair.first) ^ std::hash<T2>()(pair.second);
19 }
20};
21
22class Dataset
23{
24public:
25 using Row = int;
26 using Column = std::string;
27 using Value = int;
28 using ValueMap = std::unordered_map<std::pair<Row, Column>, Value, PairHash>;
29
30 using Ptr = std::shared_ptr<Dataset>;
31
32 explicit Dataset( const ValueMap& values) : m_values{ values }
33 {}
34 Value getContent(Row row, Column column) const
35 {
36 const auto valIt = m_values.find({ row, column });
37 return valIt != m_values.cend() ? valIt->second : Value{};
38 }
39
40private:
41 ValueMap m_values;
42};
43
44namespace bf = boost;
45
46/////////////////////////////////////////////////////////////////
47// Example of async API
48class AsyncDataProvider
49{
50 public:
51 bf::future<Dataset::Ptr> loadDataForRow(Dataset::Row row) const
52 {
53 return bf::async([&]
54 {
55 boost::this_thread::sleep_for(boost::chrono::seconds{ 2 });
56 return std::make_shared<Dataset>(Dataset::ValueMap{ { { row , "key" }, row }, { { row , "type" }, 0 } });
57 });
58 }
59};
60
61/////////////////////////////////////////////////////////////////
62int main()
63{
64 AsyncDataProvider provider{};
65
66 Dataset::Row row{ 1 };
67 // Asynchronous use (in the GUI)
68 std::cout << "Asynchronous use \n";
69 auto future = provider.loadDataForRow(row);
70 future.then([&](auto f)
71 {
72 const auto dataset = f.get();
73 std::cout << "Async getContent(): " << dataset->getContent(row, "key") << std::endl;
74 });
75
76 // Synchronous use (in the data model business logic)
77 std::cout << "Synchronous use \n";
78 auto dataset = provider.loadDataForRow(row).get();
79
80 std::cout << "Sync getContent(): " << dataset->getContent(row, "key") << std::endl;
81
82 std::cout << "end\n";
83}