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