-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathQueue_Future.cpp
More file actions
123 lines (91 loc) · 2.56 KB
/
Queue_Future.cpp
File metadata and controls
123 lines (91 loc) · 2.56 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <string>
#include <mutex>
#include <queue>
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>
#include <thread>
#include <chrono>
struct X {
int operator()(int i) {
std::cout << i << '\n';
return i + 10;
}
};
template<typename T>
class my_queue
{
private:
std::queue<T> m_queque;
mutable std::mutex m_mutex;
public:
void push(T& value )
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queque.push(std::move(value));
}
void pop()
{
std::lock_guard<std::mutex> lock(m_mutex);
m_queque.pop();
}
bool empty()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_queque.empty();
}
std::future<int> front()
{
std::lock_guard<std::mutex> lock(m_mutex);
return std::move(m_queque.front());
}
int size()
{
return m_queque.size();
}
};
int main()
{
my_queue<std::future<int>> q;
auto a = std::async(std::launch::async,X(), 1);
q.push(a);
if(!q.empty())
{
std::thread([&](){
// empty returns true if container size is 0
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
std::cout<<std::endl;
std::cout<<"----------------------------"<<q.size()<<std::endl;
std::cout<<"size "<<q.size()<<std::endl;
while(!q.empty())
{
auto p = q.front();
q.pop();
try {
std::cout<<p.get()<<std::endl;
}
catch (std::exception&) {
std::cout << "[exception caught]";
}
}
}).detach();
}
for( int i = 2; i < 100; i++)
{
auto b = std::async(std::launch::async,X(), i);
q.push(b);
}
//auto c = std::async(std::launch::async,X(), 3);
//q.push(std::move(c));
std::this_thread::sleep_for(std::chrono::milliseconds(4000));
//std::cout << a.get() << '\n';
return 0;
}