'unique_lock'에 해당되는 글 1건

  1. 2021.12.01 std::lock_guard, std::unique_lock 에서 lock, unlock 호출 시점 확인 하기

std::lock_guard, std::unique_lock 에서 lock, unlock 호출 시점 확인 하기

프로그래밍/c,c++ 2021. 12. 1. 17:50
반응형

std::lock_guard 은 생성 시점에 lock을 호출하고 소멸 시점(블럭 끝)에 unlock을 호출 한다.

 

std::unique_lock 은 생성 시점에 lock을 호출하고 소멸 시점(블럭 끝)에 unlock을 호출 하고

추가로 lock, unlock을 호출 할수 있다(lock 에 대한 상태값 유지).

 

#include <iostream>
#include <string>
#include <mutex>

class TestMutex {
    public:
        void lock() {
            std::cout << "call lock" << std::endl;
        }
        void unlock() {
            std::cout << "call unlock" << std::endl;
        }
};

TestMutex mutex1;

int main() {
    std::cout << "###### lock_guard start" << std::endl;
    {
        std::lock_guard<TestMutex> lockGuard(mutex1);
        std::cout << "lock_guard created" << std::endl;
    }
    std::cout << "###### lock_guard end" << std::endl << std::endl;

    std::cout << "###### unique_lock start" << std::endl;
    {
        std::unique_lock<TestMutex> uniqueLock(mutex1);
        std::cout << "unique_lock created" << std::endl;
    }
    std::cout << "###### unique_lock end" << std::endl << std::endl;

    std::cout << "###### unique_lock start 2" << std::endl;
    {
        std::unique_lock<TestMutex> uniqueLock(mutex1);
        std::cout << "unique_lock created" << std::endl;
        std::cout << "manual call unlock ++" << std::endl;
        uniqueLock.unlock();
        std::cout << "manual call unlock --" << std::endl;
    }
    std::cout << "###### unique_lock end 2" << std::endl << std::endl;

    std::cout << "###### unique_lock start 3" << std::endl;
    {
        std::unique_lock<TestMutex> uniqueLock(mutex1);
        std::cout << "unique_lock created" << std::endl;
        std::cout << "manual call unlock ++" << std::endl;
        uniqueLock.unlock();
        std::cout << "manual call unlock --" << std::endl;
        std::cout << "manual call lock ++" << std::endl;
        uniqueLock.lock();
        std::cout << "manual call lock --" << std::endl;
    }
    std::cout << "###### unique_lock end 3" << std::endl << std::endl;


    return 0;
}

실행 결과

$ ./a.out
###### lock_guard start
call lock
lock_guard created
call unlock
###### lock_guard end

###### unique_lock start
call lock
unique_lock created
call unlock
###### unique_lock end

###### unique_lock start 2
call lock
unique_lock created
manual call unlock ++
call unlock
manual call unlock --
###### unique_lock end 2

###### unique_lock start 3
call lock
unique_lock created
manual call unlock ++
call unlock
manual call unlock --
manual call lock ++
call lock
manual call lock --
call unlock
###### unique_lock end 3
반응형
: