[1. 원자계]
std::atomic_flag
- clear() => flag 값을 false 로
- test_and_set() => flag 값을 true 로, 읽기와 쓰기 연산이 하나의 원자계 연산으로 수행 된다.
- 최초 생성 시, ATOMIC_FLAG_INIT 상수를 이용해 false 로 초기화 해야 한다.
- 잠김 없는 유일한 원자계
- 더 높은 수준의 스레드 추상화를 위한 빌딩 블록
std::atomic_flag 를 이용한 spinlock 구현
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <atomic> | |
class Spinlock | |
{ | |
private: | |
std::atomic_flag flag; | |
public: | |
// 최초 생성 시 flag 는 false | |
Spinlock() : flag(ATOMIC_FLAG_INIT) {} | |
void lock() { | |
// flag 가 false 가 될 때 가지 대기 | |
while (flag.test_and_set()); | |
} | |
void unlock() { | |
// flag 를 false 로 변경 | |
flag.clear(); | |
} | |
}; |
std::atomic<T>
'C++ > Parallel' 카테고리의 다른 글
[정리 필요] std::async (0) | 2024.04.01 |
---|