테스트 결과
위에는 lock.test 코드를 삽입한거, 아래는 lock.test 코드를 뺀거.
테스트 코드, msvc, c++20, 최적화는 -O2
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
#include <chrono>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
constexpr int THREAD_MAX_SUM_COUNt = 10;
constexpr int MAX_SUM = 100000000;
int gSum = 0;
void f(int n)
{
while (1)
{
while (lock.test_and_set(std::memory_order_acquire)) { // acquire lock
// Since C++20, it is possible to update atomic_flag's
// value only when there is a chance to acquire the lock.
// See also: https://stackoverflow.com/questions/62318642
while (lock.test(std::memory_order_relaxed)) // test lock
; // spin
}
if (++gSum >= MAX_SUM)
{
lock.clear(std::memory_order_release); // release lock
return;
}
lock.clear(std::memory_order_release); // release lock
}
}
void f2(int n)
{
while (1)
{
while (lock.test_and_set(std::memory_order_acquire)) { // acquire lock
}
if (++gSum >= MAX_SUM)
{
lock.clear(std::memory_order_release); // release lock
return;
}
lock.clear(std::memory_order_release); // release lock
}
}
int main()
{
std::cout << "Start : with lock.test" << std::endl;
auto begin = std::chrono::high_resolution_clock::now();
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n);
}
for (auto& t : v) {
t.join();
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << gSum << std::endl;
std::cout << "End : " << (end-begin).count()/1000000 << std::endl;
std::cout << "Start : without lock.test" << std::endl;
begin = std::chrono::high_resolution_clock::now();
gSum = 0;
std::vector<std::thread> v2;
for (int n = 0; n < 10; ++n) {
v2.emplace_back(f2, n);
}
for (auto& t : v2) {
t.join();
}
end = std::chrono::high_resolution_clock::now();
std::cout << gSum << std::endl;
std::cout << "End : " << (end - begin).count() / 1000000 << std::endl;
}
차이 꽤 나네
ㅇㅇㅋ
신기하네 처음 알게됨 - dc App