-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.cpp
More file actions
56 lines (41 loc) · 1.14 KB
/
async.cpp
File metadata and controls
56 lines (41 loc) · 1.14 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
// examples in 03_cmake shows more things but is not finished yet
#include <iostream>
#include <vector>
#include <string>
#include <future>
#include <thread>
class MyClass
{
public:
void modifyVecAsync() {
std::future<void> future = std::async(std::launch::async, &MyClass::modifyVec, this);
std::future<void> f2 = std::async(std::launch::async, &MyClass::modifyStr, this, "Async");
future.get(); // wait for the async func to complete
}
void modifyVec() {
for (int i = 0 ; i < 10; i++) {
vec.push_back(i);
std::cout << "added " << i << " to the vector" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
void modifyStrAsync() {
std::future<void> future = std::async(std::launch::async, &MyClass::modifyStr, this, "Async");
// future.get(); // wait for the async func to complete
}
void modifyStr(const std::string& suffix) {
str += suffix;
std::cout << "modified string: " << str << std::endl;
}
private:
std::string str;
std::vector<int> vec;
};
int main()
{
MyClass obj;
obj.modifyVecAsync();
obj.modifyStrAsync();
std::this_thread::sleep_for(std::chrono::seconds(5));
return 0;
}