C++

    [Thread] Deadlock, std::scoped_lock

    [Thread] Deadlock, std::scoped_lock

    Deadlock 말 그대로 Lock이 죽었다라는 의미인데, thread들이 mutex lock이 해제되길 영원히 기다리는 상태를 뜻한다. Example Code std::mutex mtx; void deadlockFn() { const std::lock_guard lck(mtx); const std::lock_guard lck2(mtx); } int main() { std::thread t1(deadlockFn); t1.join(); std::cout

    [Thread] std::unique_lock

    [Thread] std::unique_lock

    std::unique_lock std::lock_guard와 비슷하지만 더 많은 기능을 가지고 있다. Example Code #include #include #include #include struct MInt { std::mutex mtx; int num = 0; }; void plus1(MInt& mi) { std::unique_lock lck(mi.mtx); mi.num++; } int main() { MInt mi; std::thread t1(plus1, std::ref(mi)); std::thread t2(plus1, std::ref(mi)); t1.join(); t2.join(); std::cout

    [Thread] std::mutex

    [Thread] std::mutex

    std::mutex cppreference 참고 Lock - mutex가 이미 Lock상태일 때 다시 Lock을 거는 행위는 Undefined 되어있다. Unlock - mutex를 Unlock할 때 Lock되어있지 않는 행위는 Undefined 되어있다. Example Code #include #include #include #include struct MInt { std::mutex mtx; int num = 0; }; void plus1(MInt& mi) { mi.mtx.lock(); // mi.mtx.lock(); // 1. 락을 2번 거는 행위 mi.num++; mi.mtx.unlock(); // 2. 락을 걸지 않았는데 unlock을 시도 } int main() { MInt mi; std::t..

    [Thread] Mutex(뮤텍스)

    [Thread] Mutex(뮤텍스)

    Mutex(뮤텍스)란? mutex란 Data race를 해결하는 가장 기초적인 방법이다. mutex는 Data race뿐 아니라 Race condition까지 해결해준다. 더보기 Race condition 공유되는 메모리 공간과는 상관 없이 thread가 어떠한 순서로 엮이느냐에 따라 결과값이 달라질 때 발생한다. Example Code #include #include #include #include void printThreadID() { std::cout

    [Thread] std::jthread (조이닝 쓰레드)

    [Thread] std::jthread (조이닝 쓰레드)

    std::jthread (C++20)란? C++20부터 추가가 되었기 때문에 아직 범용적으로 사용되고 있지는 않다. std::thread의 단점을 어느정도 보완했는지 정도만 알면된다. Example Code : 일반적인 thread를 사용하는 경우 void fn() { std::cout

    [Thread] thread_local

    [Thread] thread_local

    thread_local (C++11) 이란? thread_local 키워드는 global이나 static과 비슷한 기능을 한다. global과 static은 프로세스 전체의 Life Cycle을 가지고 있는 반면 thread_local로 만들어진 변수는 각각의 thread에 대한 Life Cycle을 가지게 된다. Example Code int globalNum = 0; thread_local int tlNum = 0; void fn() { int fnNum = 2; std::cout

    [Thread] std::thread Argument

    [Thread] std::thread Argument

    새로운 thread에 argument 전달 방법 바로 예제 코드를 보자. Example Code #include #include #include void fn(int a, std::string s) { std::cout

    [Thread] std::thread

    [Thread] std::thread

    std::thread thread에 대한 기본적인 내용부터 알아본다. Constructor Constructor를 보면 Thread를 동작시키기 위해서는 3번째 정의처럼 함수를 같이 넘겨줘야한다. 또한, Move Constructor는 정의가 되어있는 반면 Copy Constructor는 삭제되어있는걸 볼 수 있다. Example Code #include #include #include #include void fn() { std::cout