std::shared_lock<Mutex>:: lock
From cppreference.net
<
cpp
|
thread
|
shared lock
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::shared_lock
| Member functions | ||||
| Shared locking | ||||
|
shared_lock::lock
|
||||
| Modifiers | ||||
| Observers | ||||
| Non-member functions | ||||
|
void
lock
(
)
;
|
(C++14 이후) | |
연결된 뮤텍스를 공유 모드로 잠급니다. 효과적으로 mutex ( ) - > lock_shared ( ) 를 호출합니다.
목차 |
매개변수
(없음)
반환값
(없음)
예외
- mutex ( ) - > lock_shared ( ) 에 의해 발생하는 모든 예외.
- 연관된 뮤텍스가 없는 경우, std::system_error 가 std::errc::operation_not_permitted 오류 코드와 함께 발생합니다.
-
연관된 뮤텍스가 이미 이
shared_lock에 의해 잠겨 있는 경우(즉, owns_lock 이 true 를 반환하는 경우), std::system_error 가 std::errc::resource_deadlock_would_occur 오류 코드와 함께 발생합니다.
예제
|
이 섹션은 불완전합니다
이유: shared_lock::lock의 의미 있는 사용 예시를 보여주지 않음 |
이 코드 실행
#include <iostream> #include <mutex> #include <shared_mutex> #include <string> #include <thread> std::string file = "Original content."; // 파일을 시뮬레이션함 std::mutex output_mutex; // 출력 연산을 보호하는 뮤텍스 std::shared_mutex file_mutex; // 리더/라이터 뮤텍스 void read_content(int id) { std::string content; { std::shared_lock lock(file_mutex, std::defer_lock); // 먼저 잠그지 않음 lock.lock(); // 여기서 잠금 content = file; } std::lock_guard lock(output_mutex); std::cout << "Contents read by reader #" << id << ": " << content << '\n'; } void write_content() { { std::lock_guard file_lock(file_mutex); file = "New content"; } std::lock_guard output_lock(output_mutex); std::cout << "New content saved.\n"; } int main() { std::cout << "Two readers reading from file.\n" << "A writer competes with them.\n"; std::thread reader1{read_content, 1}; std::thread reader2{read_content, 2}; std::thread writer{write_content}; reader1.join(); reader2.join(); writer.join(); std::cout << "The first few operations to file are done.\n"; reader1 = std::thread{read_content, 3}; reader1.join(); }
가능한 출력:
Two readers reading from file. A writer competes with them. Contents read by reader #1: Original content. Contents read by reader #2: Original content. New content saved. The first few operations to file are done. Contents read by reader #3: New content
참고 항목
|
연결된 뮤텍스를 잠그려 시도합니다
(public member function) |
|
|
연결된 뮤텍스를 잠금 해제합니다
(public member function) |