1+ #include < iostream>
2+ #include < memory>
3+ #include < thread>
4+ #include < chrono>
5+ #include < syncstream>
6+ using namespace std ::chrono_literals;
7+
8+ class Data {
9+ public:
10+ Data (int value = 0 ) : value_(value) {}
11+ int get_value () const { return value_; }
12+ void set_value (int new_value) { value_ = new_value; }
13+ private:
14+ int value_;
15+ };
16+
17+ std::atomic<std::shared_ptr<Data>> data = std::make_shared<Data>();
18+
19+ void writer () {
20+ for (int i = 0 ; i < 10 ; ++i) {
21+ std::shared_ptr<Data> new_data = std::make_shared<Data>(i);
22+ data.store (new_data);
23+ std::this_thread::sleep_for (100ms);
24+ }
25+ }
26+
27+ void reader () {
28+ for (int i = 0 ; i < 10 ; ++i) {
29+ if (auto sp = data.load ()) {
30+ std::cout << " 读取线程值: " << sp->get_value () << std::endl;
31+ }
32+ else {
33+ std::cout << " 没有读取到数据" << std::endl;
34+ }
35+ std::this_thread::sleep_for (100ms);
36+ }
37+ }
38+
39+ std::atomic<std::shared_ptr<int >> ptr = std::make_shared<int >();
40+
41+ void wait_for_wake_up () {
42+ std::osyncstream{ std::cout }
43+ << " 线程 "
44+ << std::this_thread::get_id ()
45+ << " 阻塞,等待更新唤醒\n " ;
46+
47+ // 等待 ptr 变为其它值
48+ ptr.wait (ptr.load ());
49+
50+ std::osyncstream{ std::cout }
51+ << " 线程 "
52+ << std::this_thread::get_id ()
53+ << " 已被唤醒\n " ;
54+ }
55+
56+ void wake_up () {
57+ std::this_thread::sleep_for (5s);
58+
59+ // 更新值并唤醒
60+ ptr.store (std::make_shared<int >(10 ));
61+ ptr.notify_one ();
62+ }
63+
64+ int main () {
65+ // std::thread writer_thread{ writer };
66+ // std::thread reader_thread{ reader };
67+
68+ // writer_thread.join();
69+ // reader_thread.join();
70+
71+ // std::atomic<std::shared_ptr<int>> ptr = std::make_shared<int>(10);
72+ // std::atomic_ref<int> ref{ *ptr.load() };
73+ // ref = 100; // 原子地赋 100 给被引用的对象
74+ // std::cout << *ptr.load() << '\n';
75+ std::thread t1{ wait_for_wake_up };
76+ wake_up ();
77+ t1.join ();
78+ }
0 commit comments