如何正常停止长执行线程? [英] How to stop long executing threads gracefully?
问题描述
在这种情况下,首选的做法是什么?我可以立即杀死线程吗?
首选方法是修改代码,使其不阻止而不检查取消。
由于您无法修改代码,您不能这样做;你必须使用后台操作(但是您可以将其从任何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屋!