首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

C++17实现的读写锁「建议收藏」

1.shared_mutex和shared_lock很有意思的两个关于共享线程锁的特性 #include #include<shared_mutex> #include #include #include using namespace std; class Counter { public: std::size_t Get() const { std::shared_lockstd::shared_mutex lock(mtx); return value_; } void Increase() { std::unique_lockstd::shared_mutex lock(mtx); value_++; } void Reset() { std::unique_lockstd::shared_mutex lock(mtx); value_=0; } private: mutable std::shared_mutex mtx; std::size_t value_ = 0; }; std::mutex g_mtx; void worker(Counter &counter) { for (int i = 0; i < 3; i++) { counter.Increase(); std::size_t value = counter.Get(); std::lock_guardstd::mutex lock(g_mtx); cout << std::this_thread::get_id() << ” ” << value << endl; } } int main() { const std::size_t size = 2; Counter counter; vectorstd::thread v; v.reserve(size); v.emplace_back(worker, std::ref(counter)); v.emplace_back(worker, std::ref(counter)); for (std::thread &t : v) { t.join(); } system(“pause”); return 0; }

01
领券