반응형
std::atomic_flag는 원자적 Boolean 형입니다. std :: atomic의 모든 특수화와 달리, lock-free가 보장됩니다. std :: atomic <bool>과 달리 std :: atomic_flag는로드 또는 저장 작업을 제공하지 않습니다.
아래 예제는 atomic_flag를 이용해 lock을 얻고 해제하는 간단한 예제입니다. atomic_flag는 매우 쉽게 사용할 수 있습니다. test_and_set() 메서드와 clear() 메서드를 이용해 Lock을 얻거나 해제할 수 있습니다. 그리고 최초 atomic_flag 상수는 ATOMIC_FLAG_INIT으로 초기화 해야합니다 :D
linuxias@test $ g++ -std=c++11 atomic_flag.cpp -o atomic_flag -lpthread
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> #include <thread> #include <vector> #include <atomic> using namespace std; std::atomic_flag lock = ATOMIC_FLAG_INIT; static int index; void func(int n) { for (int cnt = 0; cnt < 10; ++cnt) { while (lock.test_and_set(std::memory_order_acquire)); // acquire lock cout << "Output from thread " << n << " : " << index++ << endl; lock.clear(std::memory_order_release); // release lock } } int main() { std::vector<std::thread> v; for (int i = 0; i < 5; ++i) v.emplace_back(func, i); for (auto& t : v) t.join(); } | cs |
반응형
'Language > C,C++' 카테고리의 다른 글
[macro] 안전한 형변환을 위한 Macro (0) | 2018.08.09 |
---|---|
[C] #pragma pack( [show] | [push | pop] , n ) (0) | 2018.07.06 |
C언어 try-catch 흉내내기 (0) | 2018.03.19 |
[C언어] 실수형 MAX, MIN 값 (0) | 2017.11.05 |
[C] noreturn (0) | 2015.11.29 |