QThread - 尝试同步杀死qthread

时间:2014-02-19 14:56:48

标签: c++ multithreading qt mutex qthread

我一直试图这样做几天,按照示例和论坛提示。

情况如下:当我调用繁重的数学函数时,我有一个冻结的GUI,这样,我想要的是将这个繁重的数学函数调度到一个线程并保持GUI响应等等。到目前为止,我得到了这个,它还可以。

问题开始是因为我需要一个'kill按钮'(用户可能只想杀死它,因为他有时可能只是在意识到事情没有按照他想要的方式改变参数并启动新参数)。我也知道这不是那么推荐,线程永远不应该被杀死/终止 - 它应该自行终止 - 这里的问题是这个重要的数学函数不是我的。它是遗留代码,我没有权限更改此函数内的任何内容。

到目前为止:

1)QThread和Worker

thread = new QThread();
worker = new Worker();
worker->moveToThread(thread);
connect(worker, SIGNAL(workRequested()), thread, SLOT(start()));
connect(thread, SIGNAL(started()), worker, SLOT(doWork()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()), Qt:irectConnection); 

2) ... ...

worker->abort();

thread->wait(); 

worker->requestWork();

... ...

3)

void Worker::abort()
{
mutex.lock();
if (_working) {
_abort = true;
qDebug()<<"Request worker aborting in Thread "<<thread()->currentThreadId();
}
mutex.unlock();
}



void Worker::requestWork()
{
mutex.lock();
_working = true;
_abort = false;
qDebug()<<"Request worker start in Thread "<<thread()->currentThreadId();
mutex.unlock();

emit workRequested();
}

void Worker::doWork()
{
qDebug()<<"Starting worker process in Thread "<<thread()->currentThreadId();


qDebug() << "get current process" << ::GetCurrentProcessId();

threadId = thread()->currentThreadId();

threadForTheSimulator = thread();


mutex.lock();
bool abort = _abort;
mutex.unlock();


while (abort == false)
{
// Checks if the process should be aborted
mutex.lock();
abort = _abort;
mutex.unlock();

// heavy mathematical function
runCSimulator(numberOfArguments,contentOfArgs);


}

// Set _working to false, meaning the process can't be aborted anymore.
mutex.lock();
_working = false;
mutex.unlock();

qDebug()<<"Worker process finished in Thread "<<thread()->currentThreadId();

emit finished();
}
4)重型计算函数被命名为runCSimulator(int,args)...很明显,因为我的函数的线程doenst有一个主循环或事件,这个'abort'函数永远不被调用..它跳进函数,永远不会来从那里回来..因此,我认为我需要的是一个与GUI按钮连接的功能,它将取消:

// function triggered with the terminate button
void Worker::doTerminate()
{
// here should go the code to kill the thread started 
// The problem here is that when i try to put the code 
// to terminate or quiot here, they are assynchronous. 
// I need something synchrnous that whenever the user
// clicks the terminateButton it will shut down this thread.
}

非常感谢任何帮助!

非常感谢!

0 个答案:

没有答案