C++11 并发与多线程(四、多个线程数据共享问题)

一、创建多个线程

多个线程执行顺序是乱的,跟操作系统内部对线程的运行调度机制有关

void MyPrint(int num)
{
	cout << "子线程Id = " << std::this_thread::get_id() << endl;
	cout << num << endl;
}
int main()
{
	vector<thread> vecThread;
	for (int i = 0; i < 10; ++i)
	{
		vecThread.push_back(thread(MyPrint, i));	//创建10个线程,同时这10个线程已经开始执行
	}
	for (auto &it : vecThread)
	{
		it.join();	//等待10个线程都返回
	}
	cout << "I Love China" << endl;

    return 0;
}

二、数据共享问题分析

  1. 只读的数据,是安全稳定的 ,不需要特别的处理手段,直接读就可以
vector <int> g_vec{ 1,2,3 };	//只读数据(不同时往里面写的数据)
void MyPrint()
{
	cout << "子线程Id = " << std::this_thread::get_id() << "的数据为:"<< g_vec [0] << g_vec [1] << g_vec [2]<< endl;
}
int main()
{
	vector<thread> vecThread;
	for (int i = 0; i < 10; ++i)
	{
		vecThread.push_back(thread(MyPrint));	//创建10个线程,同时这10个线程已经开始执行
	}
	for (auto &it : vecThread)
	{
		it.join();	//等待10个线程都返回
	}
	cout << "I Love China" << endl;

    return 0;
}
  1. 有读有写的数据(列如:2个线程写,8个线程读)肯定会造成程序崩溃。(解决办法:读的时候不能写,写的时候不能读,2个线程也不能同时写),常用生活的问题(两个人定用一张票问题)

三、共享数据的保护问题

  1. 问题引出代码:多个线程同时读写共享数据
class Test
{
public:
	Test() {};
	~Test() {};

	//把收到的消息(玩家命令)入到一个队列的线程
	void InQueue()
	{
		for (int i = 0; i < 100000; ++i)
		{
			//std::this_thread::sleep_for(std::chrono::milliseconds(1000));
			cout << "插入一个元素 : " << i << endl;
			m_list.push_back(i);
		}
	}
	void OutQueue()
	{
		for (int i = 0; i < 100000; ++i)
		{
			if (!m_list.empty())
			{
				int num = m_list.front();	//返回第一个元素,但不检查元素是否存在 所以要判断是否为空
				m_list.pop_front();		//移除第一个元素,但不返回
				//考虑处理数据
				cout << "移除一个元素 : " << num << endl;
			}
			else
			{
				cout << "队列中数据为空" << endl;
			}
		}
		//
	}

private:
	list<int> m_list;	//容器(消息队列),专门用于代表玩家发过来的命令
};


int main()
{
	Test test;
	thread objIn(&Test::InQueue, &test);	//第二个参数是引用,才能保证线程里用的是同一个对象
	thread objOut(&Test::OutQueue, &test);

	objIn.join();
	objOut.join();
	cout << "I Love China" << endl;

    return 0;
}

解决问题办法:保护共享数据问题的第一个概念 “互斥量”

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值