c++11多线程并发编程学习(5)---创建多线程

一.创建多个线程:

  1 #include<iostream>
  2 #include<thread>
  3 #include<unistd.h>
  4 #include<vector>
  5 using namespace std;
  6 
  7 void fun(int i) //线程运行函数
  8 {
  9     cout<<"第"<<i<<"个线程开始执行"<<endl;
 10     cout<<"第"<<i<<"个线程结束执行"<<endl;
 11 }
 12 int main()
 13 {                                                                                                 
 14     vector<thread> threads;
 15     //启动多个线程并执行,使用容器更加方便对线程的管理
 16     for(int i = 0;i < 10; ++i)
 17     {
 18         threads.push_back(thread(fun,i));
 19     }
 20 
 21     //等待所有子线程结束,使用迭代器很方便
 22     for(auto iter = threads.begin();iter!=threads.end();++iter)
 23     {
 24         iter->join();
 25     }
 26     cout<<"process quit"<<endl;
 27     return 0;
 28 }

二.数据共享问题

只读:不影响
有读:一定要进行同步处理

共享数据案例:
网络游戏:
创建两个线程,一个收集玩家发来的命令放入队列,
另外一个负责取出命令,解析,并且执行命令


class Game{
public:
	void InMsg()
	{	
		//向队列插入指令
	}
	void OutMsg()
	{
		//从队列中取出指令
	}
private:
	list<Msg>msgRecv;
};


int main(){

Game obj;
thread inmsg(&Game::InMsg,&obj);
thread outmsg(&Game:: OutMsg,&obj);
inmsg.join();
outmsg.join();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值