C++多线程编程第十三讲--补充知识

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//(1)补充一些知识点
    //(1.1)虚假唤醒
    // wait(), notify_one(), notify_all()    使用非常频繁的接口
    // 虚假唤醒是指没有满足条件的时候被唤醒了。
    //(1.2)atomic
 
   #include<iostream>
    #include<thread>
    #include<vector>
    #include<list>
    #include<mutex>
     
    using namespace std;
     
    class A
    {
    public:
     
        atomic<int> ato;
        A()
        {
            ato = 0;
            //std::atomic<int> ato2 = ato;   //这种赋值操作是不被允许的
            //std::atomic<int> ato2(ato.load());  //正确的,需要load函数来辅助
            //ato.store(12); // 正确,用来赋值的操作。
        }
     
        //把收到的消息,入到一个队列中
        void inMsgRecvQueue()
        {
            int i;
            for (i = 0; i < 100000; ++i)
            {
                ato++;
                //ato = ato + 1;   //不是原子操作
            }
        }
     
        //把数据从消息队列中取出
        void outMsgRecvQueue()
        {
            while (true)
            {
                //
                cout << "ato = " << ato << endl;
            }
        }
     
    private:
        list<int> msgQueue;
        mutex my_mutex;       //创建一个互斥量
        std::condition_variable cond;
    };
     
    int main()
    {
        A myobj;
        thread myOutMsg(&A::outMsgRecvQueue, std::ref(myobj));   //保证线程中用的同一个对象
        thread myInMsg(&A::inMsgRecvQueue, std::ref(myobj));
        thread myInMsg2(&A::inMsgRecvQueue, std::ref(myobj));
     
        myOutMsg.join();
        myInMsg.join();
        myInMsg2.join();
     
        cout << "main thread end..." << endl;
        return 0;
    }

  

posted on   xcxfury001  阅读(12)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示