Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions submission/exercise-16/dongyeonha/ex_16.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#include <atomic>
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>

int main() {
namespace chrono = std::chrono;

// Use std::atomic
std::atomic<int> 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<chrono::milliseconds>(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<std::mutex> lck(m);
x2 += 1;
}
});

std::thread th4([&]() {
for (int i = 0; i < 100000000; ++i) {
std::lock_guard<std::mutex> 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<chrono::milliseconds>(t4 - t3);
std::cout << "Took " << dt2.count() << "ms\n";



return 0;
}