From 1f401a7235b6f1e849debc9096bad7ad42321c94 Mon Sep 17 00:00:00 2001 From: Ha-DongYeon <113656330+Ha-DongYeon@users.noreply.github.com> Date: Mon, 18 Dec 2023 16:34:46 +0900 Subject: [PATCH] Create ex_16.cpp --- submission/exercise-16/dongyeonha/ex_16.cpp | 79 +++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 submission/exercise-16/dongyeonha/ex_16.cpp diff --git a/submission/exercise-16/dongyeonha/ex_16.cpp b/submission/exercise-16/dongyeonha/ex_16.cpp new file mode 100644 index 0000000..afa0a56 --- /dev/null +++ b/submission/exercise-16/dongyeonha/ex_16.cpp @@ -0,0 +1,79 @@ +#include +#include +#include +#include +#include + +int main() { + namespace chrono = std::chrono; + + // Use std::atomic + std::atomic x1 = 0; + + auto t1 = chrono::steady_clock::now(); + + // ½Ã°£ ÃøÁ¤ + std::thread th1([&]() { + for (int i = 0; i < 100000000; ++i) { + x1.fetch_add(1); // x1 += 1 + } + }); + std::thread th2([&]() { + for (int i = 0; i < 100000000; ++i) { + x1.fetch_add(1); // x1 += 1 + } + }); + + // do something + + if (th1.joinable()) { + th1.join(); + } + + if (th2.joinable()) { + th2.join(); + } + + auto t2 = chrono::steady_clock::now(); + + std::cout << x1 << '\n'; + auto dt = chrono::duration_cast(t2 - t1); + std::cout << "Took " << dt.count() << "ms\n"; + + int x2 = 0; + std::mutex m; + + auto t3 = chrono::steady_clock::now(); + + std::thread th3([&]() { + for (int i = 0; i < 100000000; ++i) { + std::lock_guard lck(m); + x2 += 1; + } + }); + + std::thread th4([&]() { + for (int i = 0; i < 100000000; ++i) { + std::lock_guard lck(m); + x2 += 1; + } + }); + + if (th3.joinable()) { + th3.join(); + } + + if (th4.joinable()) { + th4.join(); + } + + auto t4 = chrono::steady_clock::now(); + + std::cout << x2 << '\n'; + auto dt2 = chrono::duration_cast(t4 - t3); + std::cout << "Took " << dt2.count() << "ms\n"; + + + + return 0; +} \ No newline at end of file