위 그림처럼 하나의 쓰레드가 읽는 동안 다른 쓰레드도 읽어야 할 경우 shared_mutex를 사용한다.
1. std::shared_mutex를 사용하지 않은 경우
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <shared_mutex>
#include <string_view>
using namespace std::literals;
std::mutex m;
int shared_data = 0;
void Writer() {
while(1) {
m.lock();
shared_data += 1;
std::cout << "Writer : " << shared_data << std::endl;
std::this_thread::sleep_for(1s);
m.unlock();
std::this_thread::sleep_for(10ms);
}
}
void Reader(std::string_view name) {
while(1) {
m.lock();
std::cout << "Reader(" << name << "): " << shraed_data << std::endl;
std::this_thread::sleep_for(500ms);
m.unlock();
std::this_thread::sleep_for(10ms);
}
}
int main() {
std::thread t1(Writer);
std::thread t2(Reader, "A");
std::thread t3(Reader, "B");
std::thread t4(Reader, "C");
t1.join();
t2.join();
t3.join();
t4.join();
}
위 코드의 결과는
Writer : 1
Reader(A) : 1
Reader(B) : 1
Reader(C) : 1
Writer : 2
Reader(A) : 2
Reader(B) : 2
Reader(C) : 2
...
# Reader의 출력이 500ms정도의 간격으로 순차적으로 출력됨.
2. std::shared_mutex를 사용한 경우
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <shared_mutex>
#include <string_view>
using namespace std::literals;
std::shared_mutex m;
int shared_data = 0;
void Writer() {
while(1) {
m.lock();
shared_data += 1;
std::cout << "Writer : " << shared_data << std::endl;
std::this_thread::sleep_for(1s);
m.unlock();
std::this_thread::sleep_for(10ms);
}
}
void Reader(std::string_view name) {
while(1) {
m.lock_shared();
std::cout << "Reader(" << name << "): " << shraed_data << std::endl;
std::this_thread::sleep_for(500ms);
m.unlock_shared();
std::this_thread::sleep_for(10ms);
}
}
int main() {
std::thread t1(Writer);
std::thread t2(Reader, "A");
std::thread t3(Reader, "B");
std::thread t4(Reader, "C");
t1.join();
t2.join();
t3.join();
t4.join();
}
위 코드의 결과는
Writer : 1
Reader(C) : 1
Reader(B) : 1
Reader(A) : 1
Writer : 2
Reader(B) : 2
Reader(A) : 2
Reader(C) : 2
...
# Reader의 출력이 3개의 쓰레드가 동시에 됨.
728x90
'Language > C++' 카테고리의 다른 글
[C++] std::unique_lock, std::scope_lock, std::shared_lock (0) | 2025.07.09 |
---|---|
[C++] std::timed_mutex, std::recursive_mutex (1) | 2025.02.03 |
[C++] std::jthread (0) | 2025.01.06 |
[C++] std::async (0) | 2024.12.20 |
[C++] std::packaged_task (0) | 2024.12.18 |
댓글