创建多个线程、数据共享问题分析

Join
多个线程运行顺序是乱的,跟操作系统内部对线程的调度机制有关。
主线程等待子线程执行完毕后才执行

void myprint(int item)
{
	cout << "线程编号" << item << endl;
}
int main()
{
	//创建线程
	vector<thread> mythread;
	for (int i = 0; i < 10; i++)
	{
		mythread.push_back(thread(myprint, i));
	}
	for (auto iter = mythread.begin(); iter != mythread.end(); ++iter)
	{
		iter->join();
	}
	cout << "hello world" << endl;
    return 0;
}

数据共享问题分析
1.只读数据:安全稳定
2.有读有写:如果读和写一起运行,程序会崩溃。
不崩溃处理:最简单的方法就是读和写分开。
但是如果任务一直切换的,可能会有诡异的事情发生(甚至可能崩溃)

共享数据的保护案例代码:
网络游戏服务器。两个自己创建的线程,一个线程收集玩家的命令(用一个数字代表玩家的命令)。一个线程取出玩家的命令,并且执行玩家要干的动作。

class A {
	std::list<int>msgReceive;
public:
	void inMsgRecQueue()
	{
		for (int i = 0; i < 100; ++i)
		{
			cout << "inMsgRecQueue()执行,插入一个元素" << i << endl;
			msgReceive.push_back(i);
		}
	}
	void outMsgRecQuene()
	{
		for (int i = 0; i < 100; ++i)
		{
			cout << "inMsgRecQueue()执行,取出一个元素" << i << endl;
			if (msgReceive.empty())
			{
				//消息不为空
				int comeon = msgReceive.front();
				msgReceive.pop_front();
				//...其他处理
			}
			else
			{
				//消息为空
				cout << "outMsgRecQuene执行,但是消息队列为空!" << endl;
			}
		}
	}
};

int main()
{
	A a;
	std::thread myOutMsg(&A::outMsgRecQuene, &a);
	std::thread myRecMsg(&A::inMsgRecQueue, &a);

	myOutMsg.join();
	myRecMsg.join();

	cout << "hello world" << endl;
    return 0;
}

程序会崩溃。

猜你喜欢

转载自blog.csdn.net/a12345d132/article/details/84482387