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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | //(1)创建和等待多个线程 #include<iostream> #include<thread> #include<vector> using namespace std; void myprint( int num) { cout << "this thread id = " << std::this_thread::get_id() << " num = " << num << endl; } int main() { vector< thread > mythreadVec; int i; for (i = 0; i < 10; ++i) { mythreadVec.push_back( thread (myprint, i)); //创建并开始执行线程 } for ( auto & th : mythreadVec) { th.join(); } cout << "main thread end..." << endl; return 0; } //(2)数据共享问题分析 //(2.1) 只读的数据 #include<iostream> #include<thread> #include<vector> using namespace std; vector< int > g_v{ 1,2,3 }; //共享数据 void myprint() { for ( auto & i : g_v) { cout << "this thread id = " << std::this_thread::get_id() << " num = " << i << endl; } } int main() { vector< thread > mythreadVec; int i; for (i = 0; i < 10; ++i) { //创建并开始执行线程,每个线程都在读数据,这并不会造成冲突 mythreadVec.push_back( thread (myprint)); } for ( auto & th : mythreadVec) { th.join(); } cout << "main thread end..." << endl; return 0; } //(2.2) 有读有写:如果没有特殊的处理,这种情况程序会崩溃。 //(2.3) 其他案例 //数据共享 /(3)共享数据的保护案例代码 //两个创建的线程,一个线程收集命令,并将命令数据写道一个队列中。 //另外一个线程从队列中取出玩家发送过来的命令,解析,然后执行玩家需要的动作。 #include<iostream> #include<thread> #include<vector> #include<list> using namespace std; class A { public : //把收到的消息,入到一个队列中 void inMsgRecvQueue() { int i; for (i = 0; i < 100000; ++i) { cout << "push_back num = " << i << endl; msgQueue.push_back(i); //数字i就是玩家的命令。 } } //把数据从消息队列中取出 void outMsgRecvQueue() { int i; for (i = 0; i < 100000; ++i) { if (!msgQueue.empty()) { //消息不为空 int command = msgQueue.front(); msgQueue.pop_front(); //移除首元素 cout << "command = " << command << endl; } else { cout << "msgQueue is empty" << endl; } } } private : list< int > msgQueue; }; int main() { A myobj; //程序运行时会报错,因为存在myInMsg线程正在向队列中写入数据的时候,myOutMsg线程 //将队列中的数据拿出进行操作的错误。如何解决这种问题,在下一节中演示。 thread myOutMsg(&A::outMsgRecvQueue, std::ref(myobj)); //保证线程中用的同一个对象 thread myInMsg(&A::inMsgRecvQueue, std::ref(myobj)); myOutMsg.join(); myInMsg.join(); cout << "main thread end..." << endl; return 0; } |
posted on 2021-09-28 08:13 xcxfury001 阅读(66) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用