一.创建多个线程:
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;
}