본문 바로가기
프로그래밍 언어/C++

멀티 쓰레딩 - try_lock

by 규봉봉이 2025. 5. 13.

여러 쓰레드에서 하나의 mutex를 사용할 때, 이 mutex를 어떻게 공유할 수 있을까? 이러한 상황에 try_lock을 사용할 수 있다.

 

#include <chrono>
#include <mutex>
#include <thread>
#include <iostream>

std::chrono::milliseconds interval(50);

std::mutex mutex;
int job_shared = 0;
int job_exclusive = 0;

void worker0() {
    std::this_thread::sleep_for(interval);

    while (true) {
        if (mutex.try_lock()) {
            std::cout << "Shared (" << job_shared << ")\n";
            mutex.unlock();
            return;
        } else {
            ++job_exclusive;
            std::cout << "Exclusive (" << job_exclusive << ")\n";
            std::this_thread::sleep_for(interval);
        }
    }
}

void worker1() {
    mutex.lock();
    std::this_thread::sleep_for(10 * interval);
    ++job_shared;
    mutex.unlock();
}

int main() {
    std::thread t1(worker0);
    std::thread t2(worker1);

    t1.join();
    t2.join();
}

 

worker0와 worker1이 있는데 worker1이 mutex를 계속해서 점유하고 있다. 즉, 임계 구역을 계속하여 점유하고 있다. worker0는 worker1이 임계 구역을 점유하고 있는지 확인하고 점유하고 있지 않을때, 자신이 임계구역을 소유하도록 하였다.

 

worker0의 코드를 자세히 보겠다.

while (true) {
    if (mutex.try_lock()) { 
        std::cout << "Shared (" << job_shared << ")\n";
        mutex.unlock();
        return;
    } else { // blocking 되지 않음, 해당 블럭은 블럭킹 되지 않는 작업 수행
        ++job_exclusive;
        std::cout << "Exclusive (" << job_exclusive << ")\n";
        std::this_thread::sleep_for(interval);
    }
}

 try_lock()에서 false를 받으면 블럭킹이 되지 않는 작업을 수행하고 true를 받으면 자동으로 블럭킹이 된다. 이 방식은 CPU를 계속 사용하는 busy-waiting 방식이며, 단순한 데모에는 적합하지만 실제 환경에서는 비효율적이다.

'프로그래밍 언어 > C++' 카테고리의 다른 글

countDownLatch는 언제 쓰는게 좋을까?  (0) 2025.05.14
멀티쓰레딩 - Condition Variable  (0) 2025.05.13
멀티 쓰레딩 - std::lock_guard  (0) 2025.05.12
싱글턴 패턴 적용  (0) 2024.08.21
std::count_if  (1) 2024.07.23