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;
}
C++17实现的读写锁
最新推荐文章于 2024-06-04 10:16:55 发布