-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadWithMemberFunction.cpp
More file actions
68 lines (52 loc) · 1.42 KB
/
threadWithMemberFunction.cpp
File metadata and controls
68 lines (52 loc) · 1.42 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
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
class MyClass {
public:
int value;
MyClass() { } //default constructor
MyClass(int i) : value(i) {} //constructor
void f1(int& a, int b) {
value++;
a++;
cout << a * b << endl;
}
};
class MyFunctor {
public:
int value;
MyFunctor() {}
MyFunctor(int i) : value(i) {}
void operator() (int& a, int b) {
value++;
a++;
cout << a + b << endl;
}
};
int main() {
int x{ 10 }, y{ 20 };
MyClass m1(100);
thread t1{ &MyClass::f1, ref(m1), ref(x), y };//&m1 will also work for call (pass) by ref
//m1 with ref or & will be call (pass) by ref;
//m1 without ref or & will be call (pass) by value
//Replaing ref(x) with &ref will cause errors.
this_thread::sleep_for(chrono::seconds(1));
cout << "value = " << m1.value << " " << "x = " << x << endl;
t1.join();
MyFunctor m2(1000);
thread t2{ ref(m2), ref(x), y };
//m2 without ref will give you call (pass) by value
//m2 with ref will give you call (pass) by ref
//&m2 will lead to error
t2.join();
cout << "value = " << m2.value << " " << "x = " << x << endl;
MyClass* p1 = new MyClass(500);
thread t3{ &MyClass::f1, ref(*p1), ref(x), y };
//p1 and ref(*p1) will both give you call by ref
//*p1 will give you call by value
t3.join();
//detach before child thread completes can lead to unpredictable results.
cout << "value = " << p1->value << " " << "x = " << x << endl;
return 0;
}