当前位置: 代码迷 >> QT开发 >> qt线程里面run函数用while循环,使用terminate就发生段异常,求教
  详细解决方案

qt线程里面run函数用while循环,使用terminate就发生段异常,求教

热度:115   发布时间:2016-04-25 05:00:44.0
qt线程里面run函数用while循环,使用terminate就发生段错误,求教
RT,我就是定义了一个线程类,定义了他的run函数,函数里面使用了while循环,我通过一个按钮start这个线程,通过另外一个使用terminate结束线程,但发生段错误,这是为什么,求指教

------解决方案--------------------
尽量不要使用terminate,可以设置一个标志,在while循环中检查这个标志来判断是否需要结束线程。
------解决方案--------------------
Copied from the doc:

void QThread::terminate () [slot]

Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating systems scheduling policies. Use QThread::wait() after terminate() for synchronous termination.

When the thread is terminated, all threads waiting for the thread to finish will be woken up.

Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.

Termination can be explicitly enabled or disabled by calling QThread::setTerminationEnabled(). Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of QThread::setTerminationEnabled() for more information.

------解决方案--------------------
帮助手册中提到了
调用terminate()后,线程可能不会立即结束
之后加个
wait()
以此来等待线程的结束。