What is a safe way to stop a running thread?

后端 未结 2 629
滥情空心
滥情空心 2020-12-01 19:11

I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this

2条回答
  •  悲哀的现实
    2020-12-01 19:32

    Well from you question and subsequent comments I can suggest you two options, with some additional "warnings":

    1. If your thread loops executing something on each iteration, you can set a volatile boolean flag such that it exits after finishing the current iteration (pseudocode because I'm not familiar with python):

      while shouldExit = false
          // do stuff
      

      Then just set the flag to true when you want the thread to stop and it will stop the next time it checks the condition.

    2. If you cannot wait for the iteration to finish and need to stop it immediately, you could go for Thread.Abort, but make absolutely sure that there is no way you can leave open file handles, sockets, locks or anything else like this in an inconsistent state.

提交回复
热议问题