-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.cpp
More file actions
106 lines (95 loc) · 2.5 KB
/
example.cpp
File metadata and controls
106 lines (95 loc) · 2.5 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
#include <iostream>
#include <thread>
#include "AutoLock.h"
#include "Profiler.h"
using namespace std;
mutex printLock;
/*
sayThreeTimes is a function that will take a message and print it out three
times. It has no locking mechanism and as such, if it is ran on multiple
threads messages may merge together.
*/
void sayThreeTimes(std::string msg)
{
PROFILE_SCOPE(msg);
for (int i = 0; i < 3; i++) {
std::cout << "Task says: ";
std::cout << msg;
std::cout << std::flush;
}
}
/*
sayThreeTimesManualLock is the same as sayThreeTimes, but it uses AutoLock's
manual locking function. "PRINT" could be any string of alphabetical characters
and any "LOCK/UNLOCK(x)" statement with that same string will interact with it.
*/
void sayThreeTimesManualLock(std::string msg)
{
LOCK(PRINT);
PROFILE_SCOPE(msg);
for (int i = 0; i < 3; i++) {
std::cout << "Task says: ";
std::cout << msg;
std::cout << std::flush;
}
UNLOCK(PRINT);
}
/*
sayThreeTimesScopeLock is the same as sayThreeTimesManualLock but instead of
unlocking manually, the lock is locked with SCOPELOCK is called, and unlocks when
the program exits scope (by use of the automatic destructor call) automatically.
*/
void sayThreeTimesScopeLock(std::string msg)
{
LOCK_SCOPE(PRINT);
PROFILE_SCOPE(msg);
for (int i = 0; i < 3; i++) {
std::cout << "Task says: ";
std::cout << msg;
std::cout << std::flush;
}
}
int main(int argc, char *argv[]) {
PROFILE_SCOPE(main);
{
PROFILE_SCOPE(first);
std::thread t1(sayThreeTimes, "-----\n");
std::thread t2(sayThreeTimes, "^^^^^\n");
std::thread t3(sayThreeTimes, "00000\n");
std::thread t4(sayThreeTimes, "!!!!!\n");
std::thread t5(sayThreeTimes, "$$$$$\n");
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
}
std::cout << endl << endl;
{
PROFILE_SCOPE(second);
std::thread l1(sayThreeTimesManualLock, "-----\n");
std::thread l2(sayThreeTimesManualLock, "^^^^^\n");
std::thread l3(sayThreeTimesManualLock, "00000\n");
std::thread l4(sayThreeTimesManualLock, "!!!!!\n");
std::thread l5(sayThreeTimesManualLock, "$$$$$\n");
l1.join();
l2.join();
l3.join();
l4.join();
l5.join();
}
std::cout << endl << endl;
{
PROFILE_SCOPE(third);
std::thread s1(sayThreeTimesScopeLock, "-----\n");
std::thread s2(sayThreeTimesScopeLock, "^^^^^\n");
std::thread s3(sayThreeTimesScopeLock, "00000\n");
std::thread s4(sayThreeTimesScopeLock, "!!!!!\n");
std::thread s5(sayThreeTimesScopeLock, "$$$$$\n");
s1.join();
s2.join();
s3.join();
s4.join();
s5.join();
}
}