多线程学习之数据竞争与互斥对象

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <thread>
#include  <string>
#include <mutex>
#include <fstream>

class locfFile
{
public:
	locfFile(){
		f.open("log.txt");	//构造函数打开log.tex文件
	}
	void shared_print(std::string id, int value){
		std::lock_guard<std::mutex> loker(m_mutex);
		f << "from" << id << ":" << value << std::endl;
	}
protected:
private:
	std::mutex m_mutex;
	std::ofstream f;      //被m_mutex保护的对象
};

void function_1(locfFile& log){
	for (int i = 0; i > -100; i--){
		log.shared_print("from t1:" ,i);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	locfFile log;
	std::thread t1(function_1,std::ref(log));
	for (int i = 0; i < 100; i++)
		log.shared_print("from main:" ,i);
	
	t1.join();

	system("PAUSE"); 
	return 0;
}

效果:

fromfrom t1::0
fromfrom main::0
fromfrom t1::-1
fromfrom main::1
fromfrom t1::-2
fromfrom main::2
fromfrom t1::-3
fromfrom main::3
fromfrom t1::-4
fromfrom main::4
fromfrom t1::-5
fromfrom main::5
fromfrom t1::-6
fromfrom main::6
fromfrom t1::-7
fromfrom main::7
fromfrom t1::-8
fromfrom main::8
fromfrom t1::-9
fromfrom main::9
fromfrom t1::-10

..........

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值