diff options
author | crupest <crupest@outlook.com> | 2021-06-11 10:43:00 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2021-06-11 10:43:00 +0800 |
commit | 864c09033f17904640fc17e571a50ab64f8f225d (patch) | |
tree | 0023bef179062292cb9e9fd3b455a7af8f4f5d91 /operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp | |
parent | 10b7a5e29e48b874dbec2732c0396160bdcd5b01 (diff) | |
download | life-864c09033f17904640fc17e571a50ab64f8f225d.tar.gz life-864c09033f17904640fc17e571a50ab64f8f225d.tar.bz2 life-864c09033f17904640fc17e571a50ab64f8f225d.zip |
...
Diffstat (limited to 'operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp')
-rw-r--r-- | operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp b/operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp new file mode 100644 index 0000000..0068082 --- /dev/null +++ b/operating-system-experiment/SemaphoreAvoidDataRaceDemo.cpp @@ -0,0 +1,36 @@ +#include "Semaphore.h" +#include "Thread.h" + +#include <iostream> + +int main() { + unsigned data = 0; + + cru::Semaphore semaphore; + + cru::Thread t1([&data, &semaphore] { + for (int i = 0; i < 100000; i++) { + semaphore.P(); + data += 10; + semaphore.V(); + } + }); + + cru::Thread t2([&data, &semaphore] { + for (int i = 0; i < 100000; i++) { + semaphore.P(); + data += 10; + semaphore.V(); + } + }); + + std::cout << "Created thread: " << t1.GetNativeID() << '\n'; + std::cout << "Created thread: " << t2.GetNativeID() << '\n'; + + t1.Join(); + t2.Join(); + std::cout << "Answer is " << data << ", which is " + << (data == 2000000 ? "correct" : "false") << '\n'; + + return 0; +} |