unique_lock 이란?

 

  • unique_lock 객체는 lock_guard와 같이 RAII 기법을 통해 생성자에서 락에 대한 소유권을 획득하고 소멸자에서 락에 대한 소유권을 반환하는 객체입니다.

 

  • unique_lock을 생성할 때 derfer_lock, try_to_lock, adopt_lock 중 하나를 추가로 전달하여 lock_guard보다 다양한 기능을 사용할 수 있습니다.

 

  • lock_guard가 상대적으로 unique_lock 보다 더 가볍기 때문에 lock_guard를 우선적으로 사용하고 필요시에 unique_lock을 사용하는 것이 좋습니다.




defer_lcok

 

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

int num;
std::mutex m;

void WorkerThread() {
    for (int i = 0; i < 100000; ++i)
    {
        std::unique_lock<std::mutex> lk(m, std::defer_lock);
        lk.lock();

        ++num;
    }

    return;
}


int main()
{
    std::thread th1(WorkerThread);
    std::thread th2(WorkerThread);

    th1.join();
    th2.join();

    std::cout << num;

    return 0;
}

 

  • defer_lock을 전달할 경우 소유권 획득 시점을 생성자가 아닌 lock 멤버 함수를 호출하는 시점으로 연기할 수 있습니다. 그리고 lock이 호출되었다면, 소멸자에서 이를 반환합니다.




try_to_lock

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

int num;
std::mutex m;

void WorkerThread() {
    for (int i = 0; i < 100000; ++i)
    {
        std::unique_lock<std::mutex> lk(m, std::try_to_lock);
        if (!lk.owns_lock()) {
            --i;
            continue;
        }

        ++num;
    }

    return;
}


int main()
{
    std::thread th1(WorkerThread);
    std::thread th2(WorkerThread);

    th1.join();
    th2.join();

    std::cout << num;

    return 0;
}

 

  • try_to_lock은 생성자에서 lock에 대한 소유권을 획득할 수 있는지 여부를 시도를 합니다. 만약, 생성자에서 lock에 대한 소유권을 획득하였다면, owns_lock() 멤버 함수의 return 값이 true이고 획득하지 못했다면 false를 return 합니다.




adopt_lock

 

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

int num;
std::mutex m;

void WorkerThread() {
    for (int i = 0; i < 100000; ++i)
    {
        m.lock();
        std::unique_lock<std::mutex> lk(m, std::adopt_lock);
        ++num;
    }

    return;
}


int main()
{
    std::thread th1(WorkerThread);
    std::thread th2(WorkerThread);

    th1.join();
    th2.join();

    std::cout << num;

    return 0;
}

 

  • adopt_lock는 이미 매개변수로 전달한 동기화 객체에 대한 소유권이 이미 획득되어 있는 상태이고, 이를 소멸자에서 반환하기 위해서 사용합니다.




+ Recent posts