mutex

 

  • mutex는 C++11에 추가된 class로써 운영체제에 종속되지 않고 공통적으로 사용할 수 있는 유저 모드 동기화 객체입니다.

 

  • 배타적인 접근만 가능하며, 중복 락이 불가능합니다.




lock과 unlock

 

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

std::mutex m;

void WorkerThread()
{
    for (int i = 0; i < 100000; ++i)
    {
        m.lock();
        ++num;
        m.unlock();
    }

    return;
}

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

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

    std::cout << num;

    return 0;
}

 

  • lock()을 통해서 배타적인 접근이 가능하고, unlock()을 통해서 배타적인 접근에 대한 소유권 해제가 가능합니다.

 

  • try_lock()은 현재 배타적인 접근이 가능한지를 확인하고 소유권을 획득하는 멤버 함수이며, return 타입은 bool로써 소유권 획득 성공 여부를 뜻합니다.




lock_guard

 

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

int num;
std::mutex m;

void WorkerThread()
{
    for (int i = 0; i < 100000; ++i)
    {
        std::lock_guard<std::mutex> lock(m);
        ++num;
    }

    return;
}


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

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

    std::cout << num;

    return 0;
}

 

  • lock_guard 객체는 RAII 디자인 패턴을 이용해서 생성자에서 락을 획득하고 소멸자에서 락을 반환하는 객체입니다.


  • lock_guard는 복사가 불가능하기 때문에 Call-by-value 방식으로 매개 변수 또는 리턴으로 값을 전달할 수가 없습니다.




+ Recent posts