-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
98 lines (81 loc) · 2.35 KB
/
Copy pathmain.cpp
File metadata and controls
98 lines (81 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <thread>
#include <chrono>
#include <numeric>
#include "core.h"
#include "promise.h"
#include "future.h"
int main(){
std::cout<<"hello world"<<std::endl;
auto [p, f] = makePromiseContract<int>();
std::thread t([p = std::move(p)] ()mutable{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout<<"set result"<<std::endl;
p.setValue(100);
});
auto f1 = std::move(f).then([](int i){
return i*i;
}).then([](int i){
return std::to_string(i);
}).then([](std::string&& s){
return std::vector<std::string>{s,s,s,s};
}).ensure([]{
std::cout<<"ensure"<<std::endl;
});
std::cout<<"waiting for result"<<std::endl;
for (auto& value : std::move(f1).get()){
std::cout<<value<<std::endl;
}
t.join();
{
std::vector<Future<int>> futures;
for (int i = 1; i <= 10; i++){
auto [p, f] = makePromiseContract<int>();
futures.emplace_back(std::move(f));
std::thread([i, p = std::move(p)] ()mutable{
std::this_thread::sleep_for(std::chrono::seconds(i));
p.setValue(int(i));
std::cout<<"thread setValue:"<<i<<std::endl;
}).detach();
}
auto f2 = collectAll(std::move(futures)).then([](std::vector<int>&& results){
return std::accumulate(std::begin(results), std::end(results), 0);
});
std::cout<<"start wait collectAll"<<std::endl;
assert(std::move(f2).get() == 55);
}
{
std::vector<Future<int>> futures;
for (int i = 1; i <= 10; i++){
auto [p, f] = makePromiseContract<int>();
futures.emplace_back(std::move(f));
std::thread([i, p = std::move(p)] ()mutable{
p.setValue(int(i));
}).detach();
}
auto f2 = collectN(std::move(futures),9).then([](std::vector<std::pair<size_t, int>>&& results){
int sum = 0;
for(auto[index, value] : results){
sum += value;
}
return sum;
});
std::cout<<"start wait collectN"<<std::endl;
assert(std::move(f2).get() < 55);
}
{
std::vector<Future<int>> futures;
for (int i = 1; i <= 10; i++){
auto [p, f] = makePromiseContract<int>();
futures.emplace_back(std::move(f));
std::thread([i, p = std::move(p)] ()mutable{
p.setValue(int(1));
}).detach();
}
auto f2 = collectAny(std::move(futures));
std::cout<<"start wait collectAny"<<std::endl;
assert(std::move(f2).get().second == 1);
}
std::cout<<"finished"<<std::endl;
return 0;
}