분류 전체보기48 C++ Spinlock 구현 다음과 같이 스핀락을 구현하면 문제가 발생할 수 있다. class SpinLock { public: void lock() { while (mLocked) {} mLocked = true; } void unlock() { mLocked = false; } private: volatile bool mLocked = false; }; 이유는 간단하다. mLocked를 true로 set하는 부분과 mLocked가 원자적(Atomic)으로 실행되지 않기 때문이다. mLocked가 false인줄 알고 while문을 통과하고 아래로 내려갔는데, 동시에 다른 스레드에서 mLocked를 true로 set하기 전에 mLocked를 통과할 가능성 또한 존재한다. 이런 상황에서는 atomic 변수 내부의 Compare and.. 2023. 3. 11. C++ / std::promise, std::future #include #include #include #include #include using std::string; void worker(std::promise* p) { try { throw std::runtime_error("Some Error!"); } catch (...) { // set_exception 에는 exception_ptr 를 전달해야 한다. p->set_exception(std::current_exception()); } } int main() { std::promise p; // 미래에 string 데이터를 돌려 주겠다는 약속. std::future data = p.get_future(); std::thread t(worker, &p); // 미래에 약속된 데이터를 받을 때 까지 기.. 2023. 2. 18. C++ / std::atomic std::atomic은 해당 객체가 원자적으로 처리될 수 있도록 도와주는 객체다. #include #include #include #include void worker(std::atomic& counter) { for (int i = 0; i < 10000; i++) { counter++; } } int main() { std::atomic counter(0); std::vector workers; for (int i = 0; i < 4; i++) { workers.push_back(std::thread(worker, ref(counter))); } for (int i = 0; i < 4; i++) { workers[i].join(); } std::cout 2023. 2. 17. C++ 11 / mutex를 활용한 동기화 #include #include // mutex 를 사용하기 위해 필요 #include #include void worker(int& result, std::mutex& m) { for (int i = 0; i < 10000; i++) { m.lock(); result += 1; m.unlock(); } } int main() { int counter = 0; std::mutex m; std::vector workers; for (int i = 0; i < 4; i++) { workers.push_back(std::thread(worker, std::ref(counter), std::ref(m))); } for (int i = 0; i < 4; i++) { workers[i].join(); } std::.. 2023. 2. 16. 이전 1 2 3 4 ··· 12 다음