如何正常停止长执行线程? [英] How to stop long executing threads gracefully?

查看:171
本文介绍了如何正常停止长执行线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Delphi的线程问题。我想这在其他语言中也是常见的。我有一个很长的过程,我在一个线程中,填充主窗口中的列表。但是如果某些参数在平均时间内变化,那么我应该停止当前执行的线程并从头开始。 Delphi建议通过设置Terminated:= true并在线程中检查此变量的值来终止线程。但是我的问题是这个,长执行部分被埋在一个库调用中,在这个调用中我不能检查Terminated变量。因此,我不得不等待这个库调用完成,影响整个程序。



在这种情况下,首选的做法是什么?我可以立即杀死线程吗?

解决方案

首选方法是修改代码,使其不阻止而不检查取消。



由于您无法修改代码,您不能这样做;你必须使用后台操作(但是您可以将其从任何UI中取消关联,以使其完成将被忽略);或者,您可以尝试终止它(TerminateThread API将粗暴地终止给定其句柄的任何线程)。终端不干净,但是,像Rob所说,线程持有的任何锁将被放弃,任何被这样的锁保护的交叉线程状态可能处于破坏状态。


$ b $你可以考虑在单独的可执行文件中调用该函数吗?也许使用RPC(管道,TCP,而不是共享内存,由于相同的锁定问题),以便您可以终止进程,而不是终止线程?过程隔离将给您更多的保护。只要你不依赖交叉进程命名的东西,如互斥体,它应该比杀死一个线程更安全。


I have a threading problem with Delphi. I guess this is common in other languages too. I have a long process which I do in a thread, that fills a list in main window. But if some parameters change in the mean time, then I should stop current executing thread and start from the beginning. Delphi suggests terminating a thread by setting Terminated:=true and checking for this variable's value in the thread. However my problem is this, the long executing part is buried in a library call and in this call I cannot check for the Terminated variable. Therefore I had to wait for this library call to finish, which affects the whole program.

What is the preferred way to do in this case? Can I kill the thread immediately?

解决方案

The preferred way is to modify the code so that it doesn't block without checking for cancellation.

Since you can't modify the code, you can't do that; you either have to live with the background operation (but you can disassociate it from any UI, so that its completion will be ignored); or alternatively, you can try terminating it (TerminateThread API will rudely terminate any thread given its handle). Termination isn't clean, though, like Rob says, any locks held by the thread will be abandoned, and any cross-thread state protected by such locks may be in a corrupted state.

Can you consider calling the function in a separate executable? Perhaps using RPC (pipes, TCP, rather than shared memory owing to same lock problem), so that you can terminate a process rather than terminating a thread? Process isolation will give you a good deal more protection. So long as you aren't relying on cross-process named things like mutexes, it should be far safer than killing a thread.

这篇关于如何正常停止长执行线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆