c++11 mutex destroy while busy

本文探讨了使用C++实现线程安全的操作时遇到的问题及解决方法。通过对比直接在主线程中调用与通过线程调用的方式,揭示了线程同步机制的重要性,并附带了一个简单的示例程序。
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <conio.h>


using std::cout;
using std::endl;
using std::thread;
using std::mutex;


mutex m;
int op;


void waitKey();
void move();



int main()
{

	thread threadKey(waitKey);
	threadKey.detach();//分离线程


	while (true){
		//thread threadMove(move);
		//threadMove.join();//移动
		move();
	}


	return 0;
}

void waitKey()
{
	int num;
	while (true){
		num = getch();
		m.lock();
		op = num;
		m.unlock();

	}
}

void move()
{
	int num = 0;


	//防止阻塞当前线程
	if (m.try_lock()){
		num = op;
		op = 0;
		m.unlock();
	}

}



环境:vs2013

直接在主线程中调用move操作op,当我关闭控制台时就会弹出错误。

将move换成线程调用,解决问题。


还不是很清楚原因。

下面是StackOverflow的解答:

http://stackoverflow.com/questions/28529018/thread-safe-stack-mutex-destroyed-while-busy



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值