forked from alicjab/registration-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
etam.cpp
71 lines (59 loc) · 1.41 KB
/
etam.cpp
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
#include <algorithm>
#include <functional>
#include <future>
#include <iostream>
#include <mutex>
#include <utility>
#include <vector>
template <class T>
class monitor
{
private:
mutable T obj;
mutable std::mutex access;
T synced_obj_copy() const
{
std::lock_guard<std::mutex> lock{access};
return obj;
}
public:
monitor() = default;
monitor(const T& _obj)
: obj(_obj)
{}
monitor(T&& _obj)
: obj{std::move(_obj)}
{}
monitor(const monitor<T>& other_monitor)
: obj{other_monitor.synced_obj_copy()}
{}
monitor& operator=(const monitor& other_monitor)
{
{
std::lock_guard<std::mutex> lock{access};
obj = other_monitor.synced_obj_copy();
}
return *this;
}
template <typename F>
auto operator()(F f) const -> decltype(f(obj))
{
std::lock_guard<std::mutex> lock{access};
return f(obj);
}
};
monitor<std::reference_wrapper<std::ostream>> synced_cout{{std::cout}};
int main()
{
const auto name = {'e', 't', 'a', 'm'};
auto futures = std::vector<std::future<void>>{};
for (char c : name)
futures.emplace_back(std::async(std::launch::async, [c]{
synced_cout([c](std::ostream& ostream) {
ostream << c;
});
}));
for (std::future<void>& future : futures)
future.wait();
return 0;
}