thread_lock_tag
thread_lock_tag (뮤텍스 잠금 태그)
이 페이지는 C++ 표준 라이브러리의 잠금 태그 타입과 상수에 대해 설명해요. std::defer_lock_t, std::try_to_lock_t, std::adopt_lock_t는 각각 std::lock_guard나 std::unique_lock과 같은 잠금 관리 객체의 생성자에 전달되어 잠금 동작 방식을 지정하는 태그로 사용돼요. 이 태그들을 사용하면 뮤텍스 잠금을 더 세밀하게 제어할 수 있어요.
출처: cppreference
본문
정의
| struct defer_lock_t { explicit defer_lock_t () = default ; }; | (1) | (since C++11) |
| constexpr std :: defer_lock_t defer_lock {}; | (2) | (since C++11) (inline since C++17) |
| struct try_to_lock_t { explicit try_to_lock_t () = default ; }; | (3) | (since C++11) |
| constexpr std :: try_to_lock_t try_to_lock {}; | (4) | (since C++11) (inline since C++17) |
| struct adopt_lock_t { explicit adopt_lock_t () = default ; }; | (5) | (since C++11) |
| constexpr std :: adopt_lock_t adopt_lock {}; | (6) | (since C++11) (inline since C++17) |
std::lock_guard 클래스 템플릿의 생성자 중 하나는 std::adopt_lock 태그만 받아들여요.
태그의 효과
| 타입 | 효과 |
|---|---|
| defer_lock_t | 뮤텍스의 소유권을 획득하지 않아요. |
| try_to_lock_t | 블로킹 없이 뮤텍스의 소유권을 획득하려고 시도해요. |
| adopt_lock_t | 호출 스레드가 이미 뮤텍스의 소유권을 가지고 있다고 가정해요. |
이 태그들은 std::lock_guard나 std::unique_lock의 생성자에 전달되어 잠금 방식을 결정해요. 예를 들어 std::adopt_lock을 사용하면 이미 잠긴 뮤텍스의 소유권을 넘겨받고, std::defer_lock을 사용하면 나중에 직접 잠글 수 있게 해요.
예제
#include <iostream>
#include <mutex>
#include <thread>
struct bank_account
{
explicit bank_account(int balance) : balance{balance} {}
int balance;
std::mutex m;
};
void transfer(bank_account& from, bank_account& to, int amount)
{
if (&from == &to) // avoid deadlock in case of self transfer
return;
// lock both mutexes without deadlock
std::lock(from.m, to.m);
// make sure both already-locked mutexes are unlocked at the end of scope
std::lock_guard lock1{from.m, std::adopt_lock};
std::lock_guard lock2{to.m, std::adopt_lock};
// equivalent approach:
// std::unique_lock<std::mutex> lock1{from.m, std::defer_lock};
// std::unique_lock<std::mutex> lock2{to.m, std::defer_lock};
// std::lock(lock1, lock2);
from.balance -= amount;
to.balance += amount;
}
int main()
{
bank_account my_account{100};
bank_account your_account{50};
std::thread t1{transfer, std::ref(my_account), std::ref(your_account), 10};
std::thread t2{transfer, std::ref(your_account), std::ref(my_account), 5};
t1.join();
t2.join();
std::cout << "my_account.balance = " << my_account.balance << "\n"
"your_account.balance = " << your_account.balance << '\n';
}
출력
my_account.balance = 95
your_account.balance = 55
같이 보기
| (constructor) | lock_guard를 생성하며, 주어진 뮤텍스를 선택적으로 잠가요. (std::lock_guard |
|---|---|
| (constructor) | unique_lock을 생성하며, 제공된 뮤텍스를 선택적으로 잠가요(즉, 소유권을 획득해요). (std::unique_lock |