aboutsummaryrefslogtreecommitdiff
path: root/operating-system-experiment/MutexAvoidDataRaceDemo.cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-06-10 11:35:29 +0800
committercrupest <crupest@outlook.com>2021-06-10 11:35:29 +0800
commitdf97d69a45ba4e50114458e2b5c4185460f2d9f3 (patch)
tree6eeaab0f3877dd92af2d39812c63c7bb9e5bebd9 /operating-system-experiment/MutexAvoidDataRaceDemo.cpp
parent3128281e50d30d12a053bc06018df4efcc8e988e (diff)
downloadlife-df97d69a45ba4e50114458e2b5c4185460f2d9f3.tar.gz
life-df97d69a45ba4e50114458e2b5c4185460f2d9f3.tar.bz2
life-df97d69a45ba4e50114458e2b5c4185460f2d9f3.zip
...
Diffstat (limited to 'operating-system-experiment/MutexAvoidDataRaceDemo.cpp')
-rw-r--r--operating-system-experiment/MutexAvoidDataRaceDemo.cpp42
1 files changed, 42 insertions, 0 deletions
diff --git a/operating-system-experiment/MutexAvoidDataRaceDemo.cpp b/operating-system-experiment/MutexAvoidDataRaceDemo.cpp
new file mode 100644
index 0000000..81a7aa1
--- /dev/null
+++ b/operating-system-experiment/MutexAvoidDataRaceDemo.cpp
@@ -0,0 +1,42 @@
+#include "Mutex.h"
+#include "Thread.h"
+
+#include <iostream>
+
+int main() {
+
+ unsigned data = 0;
+ cru::Mutex mutex;
+ mutex.Lock();
+
+ cru::Thread t1([&data, &mutex] {
+ for (int i = 0; i < 100000; i++) {
+ mutex.Lock();
+ data += 10;
+ //std::cout << "Data is now: " << data << '\n';
+ mutex.Unlock();
+ }
+ });
+
+ cru::Thread t2([&data, &mutex] {
+ for (int i = 0; i < 100000; i++) {
+ mutex.Lock();
+ data += 10;
+ //std::cout << "Data is now: " << data << '\n';
+ mutex.Unlock();
+ }
+ });
+
+ std::cout << "Created thread: " << t1.GetNativeID() << '\n';
+ std::cout << "Created thread: " << t2.GetNativeID() << '\n';
+
+ mutex.Unlock();
+
+ t1.Join();
+ t2.Join();
+
+ std::cout << "Answer is " << data << ", which is "
+ << (data == 2000000 ? "correct" : "false") << '\n';
+
+ return 0;
+}