多线程例子之数据竞争和互斥对象(锁、互斥量)

31 篇文章 1 订阅

代码来源自百度传课教学视频:https://chuanke.baidu.com/v3891329-172880-843280.html

意看注释。 

#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <fstream>

//std::mutex mu;
//
//void shared_print(std::string msg, int id)
//{
//	//mu.lock();//若不释放则资源会被一直占用
//	std::cout << msg << id << std::endl;//相当于对cout这个资源加锁,若此句出现了异常则资源将会被一直占用
//	//mu.unlock();
//}

class LogFile
{
public:
	LogFile()
	{
		f.open("log.txt");
	}
	void shared_print(std::string id, int value)
	{
		std::lock_guard<std::mutex> locker(m_mutex);//如果用这种方式对资源加锁有一个好处,即万一后面的语句有异常不会导致资源一直被占用,而会自动释放资源
		f << "From" << id << ":" << value << std::endl;
	}
	//std::ofstream& GetStream() { return f; };//这样就使得成员f暴露出去了,于是便失去了对该资源的保护
	//也不能把资源当参数传递
	
protected:
private:
	std::mutex m_mutex;
	std::ofstream f;//资源f是类的成员,也就是说在类的保护之下。这样的话要想用资源必须要用类,这样就起到了资源和锁绑定到一起的作用

};

void Function1(LogFile& log)
{
	for (int i = 0;i < 100;i++)
		log.shared_print("In Funtion1", i);
}

int main()
{
	LogFile log;
	std::thread t1(Function1,std::ref(log));
	for (int j = 0;j < 100;j++)
	{
		log.shared_print( "In Main" ,j);
	}
	t1.join();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值