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

被折叠的 条评论
为什么被折叠?



