使用函数
- C++11 线程:
C++多线程的6种创建方法 - C++14 shared_mutex 共享锁
C++多线程 读写锁shared_lock/shared_mutex
C++ std::shared_mutex读写锁 - C++11 多线程休眠:
C++11——多线程编程12 如何让线程在C++11中休眠
C++:详解C++11 线程休眠函数
rwlock.h
实现 读写锁
#pragma once
#include <mutex>
#include <shared_mutex>
class ReaderWriterLatch {
private:
mutable std::shared_mutex mutex_;
public:
void WLock() { mutex_.lock(); } // 获取写锁
void WUnlock() { mutex_.unlock(); } // 释放写锁
void RLock() { mutex_.lock_shared(); } // 获得读锁
void RUnlock() { mutex_.unlock_shared(); }// 释放读锁
};
main.cpp
主函数,实现多线程
#include <iostream>
#include "rwlock.h"
#include <thread>
#include <vector>
using namespace std;
ReaderWriterLatch latch;
int cnt = 0;
void read() {
while (1) {
latch.RLock();
cout << "read count, count: " << cnt << "\tpid: " << std::this_thread::get_id() << endl;
latch.RUnlock();
this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
void write() {
while (1) {
latch.WLock();
cnt++;
cout << "write count, count: " << cnt << "\tpid: " << std::this_thread::get_id() << endl;
latch.WUnlock();
this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
int main() {
// 创建多个读线程和多个写线程
int num = 5;
vector<thread> readThreads;
vector<thread> writeThreads;
for (int i = 0; i < num; i++) {
readThreads.emplace_back(read); //五个线程去执行 read()
writeThreads.emplace_back(write); // 五个线程去执行 write()
}
// 主线程阻塞 等待子线程完成任务后回收资源
for (auto& thread : readThreads) thread.join();
for (auto& thread : writeThreads) thread.join();
system("pause");
return 0;
}
结果: