您的位置:首页 > 编程语言 > Qt开发

QT中关线程的问题

2015-08-11 14:23 423 查看

一、前段时间写了个多线程的代码,当关线程的时候遇到当发送了关线程后,线程不能及时关掉,然后,影响后面的其他的线程的通信。

之前的办法如下:

void MyThread::stop()

{

mutex.lock;

t_stop = true;

mutex.unlock;

mcondition.wakeall;

}

void MyThread::run()

{

forever {

mutex.lock;

if (t_stop) {

t_stop = false;

mutex.unlock;

break;

}

mcondition.wait(&mutex, 15s);//延时15s

mutex.unlock;

dosomething();//会耗时大概10s种;uart和其他模块交互

}

}

更改后解决办法如下:

1、我的硬件平台是arm9

2、子线程里,重新实现了run函数;

t_stop 初始化为false;

大概是这样的:

void MyThread::stop()

{

mutex.lock;

t_stop = true;

mutex.unlock;

mcondition.wakeall;

}

void MyThread::run()

{

forever {

mutex.lock;

if (t_stop) {

t_stop = false;

mutex.unlock;

break;

}

mcondition.wait(&mutex, 15s);//延时15s

mutex.unlock;

mutex.lock;

if (t_stop) {

t_stop = false;

mutex.unlock;

break;

}

dosomething();//会耗时大概10s种;uart和其他模块交互

mutex.unlock;

}

}

3、然后主线程里面先打开,然后过段时间再关闭线程。

关闭:t->stop(); //MyThread t;

就如上所示的关闭线程这样正确吗?

二、这里使用了条件变量。

这样处理之后好像就没有问题了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: