반응형
atomic
<atomic>라이브러리보장하고 싶은 변수를
atomic<type>형식으로 정의하면 된다.성능이 느려진다.
- 성능을 위해 mutex를 사용하는 것 같다.
예제
atomic을 사용하지 않은 예제#include <iostream> #include <thread> #include <chrono> int main() { using namespace std; int shared_memory(0); auto count_func = [&]() { for (int i = 0; i < 1000; ++i) { this_thread::sleep_for(chrono::milliseconds(1)); shared_memory++; } }; thread t1 = thread(count_func); thread t2 = thread(count_func); t1.join(); t2.join(); cout << "Value is " << shared_memory << endl; } /* stdout stderr Value is 1997 */- 값이 2000이 아닌 1997이 나온 것을 볼 수 있다.
atomic을 사용한 예제<atomic>라이브러리를 포함하지 않아도 사용할 수 있었다.여기서
shared_memory++는atomic클래스에서 오버로딩한 연산자를 사용한다.
#include <iostream> #include <thread> #include <chrono> #include <atomic> int main() { using namespace std; atomic<int> shared_memory(0); auto count_func = [&]() { for (int i = 0; i < 1000; ++i) { this_thread::sleep_for(chrono::milliseconds(1)); shared_memory++; } }; thread t1 = thread(count_func); thread t2 = thread(count_func); t1.join(); t2.join(); cout << "Value is " << shared_memory << endl; } /* stdout stderr Value is 2000 */
반응형
'SW개발 > C++' 카테고리의 다른 글
| C++ 동시성 (Concurrency) (0) | 2021.03.30 |
|---|---|
| C++ 멀티쓰레딩 (Multithreading) (0) | 2021.03.30 |
| C++ mutex (0) | 2021.03.30 |
| C++ 람다 함수 (Lambda Function) (0) | 2021.03.30 |
| 따라하며 배우는 C++ 19장 (0) | 2021.03.30 |