简体   繁体   English

如何停止 python 中的线程,该线程本身在循环内被调用?

[英]How do I stop a thread in python which itself is being called inside a loop?

This seems like a particularly confusing question based on the other similar answers I found on SO.基于我在 SO 上找到的其他类似答案,这似乎是一个特别令人困惑的问题。 I have code similar to the following:我有类似于以下的代码:

def parentFunction():
    # Other code
    while True:
        var1, var2 = anotherFunction1() # Getting client details after listening on open port
        threading.Thread(target = anotherFunction2, args=(var1, var2)).start()
        childFunction(var1,var2)
        print("PRINT #1: Running in Parent Function") # This only prints once for some reason

def childFunction(var1, var2):
    threading.Timer(10, childFunction, args=(var1,var2)).start()
    print("PRINT #2: Running in child function") # Prints every 10 seconds
    
    # Other code 

    if (someConditionIsMet):
        print("PRINT #3: Exiting") 
        end_process_and_exit_here()

So basically, when I ran the parentFunction() , I would go into a neverending loop where ever 10 seconds, my console would print "PRINT #2: Running in child function" .所以基本上,当我运行parentFunction() ,我会进入一个永无止境的循环,每 10 秒,我的控制台就会打印"PRINT #2: Running in child function" When the someConditionIsMet was true, my console would print "PRINT #3: Exiting" but then it wouldn't exit.someConditionIsMet为真时,我的控制台会打印“PRINT #3: Exiting”,但它不会退出。 Hence, my loop would carry on forever.因此,我的循环将永远进行。 I am not sure if it's relevant, but parts of the code has a Threading.Lock as well.我不确定它是否相关,但部分代码也有一个 Threading.Lock。

Where I have written end_process_and_exit_here() above, I tried using several methods to kill a thread such as我在上面写了end_process_and_exit_here()地方,我尝试使用几种方法来杀死一个线程,例如

  1. Raising exceptions and setting flags - These assume that I have started my thread outside of my loop so it's not comparable. 引发异常和设置标志- 这些假设我已经在我的循环之外启动了我的线程,所以它没有可比性。
  2. Even this qn about looping threads assumes the thread isnt being looped 即使这个关于循环线程的 qn 也假设线程没有被循环
  3. Killing using join or stop - stop() was not an option I could access. 使用 join 或 stop 杀死- stop()不是我可以访问的选项。 join() was available but it didn't work ie after it was called, the next thread ( PRINT #2 ) continued printing. join()可用但它不起作用,即在它被调用后,下一个线程( PRINT #2 )继续打印。
  4. Other answers suggesting the use of signals (1) (2) , also didn't work.其他建议使用信号 (1) (2) 的答案也不起作用。
  5. Using sys.exit() or break in different parts of my code also did not result in the threads stopping.使用 sys.exit() 或在我的代码的不同部分中断也不会导致线程停止。

Is there any method for me to easily exit from such a looping thread?有什么方法可以让我轻松退出这样的循环线程吗?

Note: I need to use threading and not multiprocessing.注意:我需要使用线程而不是多处理。

You could use python-worker , simply add @worker above you function pip install python-worker您可以使用python-worker ,只需在函数pip install python-worker上方添加 @worker

from worker import worker

@worker
def anotherFunction2(var1,var2):
   # your code here
   pass

@worker
def parentFunction():
    # Other code
    while True:
        var1, var2 = anotherFunction1() # Getting client details after listening on open port
        function2Worker = anotherFunction2(var1,var2) # this will automatically run as thread since you put @worker above your function
        childFunction(var1,var2)
        print("PRINT #1: Running in Parent Function") # This only prints once for some reason

def childFunction(var1, var2):
    parentWorker = parentFunction(var1, var2)
    
    # Other code 

    if (someConditionIsMet):
        parentWorker.abort()

I'm not certain if this is a bad practice (in fact I feel it may be based on the answers linked in the question saying that we should never 'kill a thread').我不确定这是否是一种不好的做法(事实上,我觉得这可能是基于问题中链接的答案,说我们永远不应该“杀死线程”)。 I'm sure there are reasons why this is not good and I'd appreciate anyone telling me why.我敢肯定这不是好事是有原因的,我很感激有人告诉我原因。 However, the solution that ultimately worked for me was to use .cancel() .但是,最终对我.cancel()的解决方案是使用.cancel()

So first change would be to assign your thread Timer to a variable instead of calling it directly.因此,第一个更改是将您的线程 Timer 分配给一个变量,而不是直接调用它。 So instead of threading.Timer(10, childFunction, args=(var1,var2)).start() , it should be因此,而不是threading.Timer(10, childFunction, args=(var1,var2)).start() ,它应该是

t = threading.Timer(10, childFunction, args=(var1,var2))
t.start()

Following that, instead of end_process_and_exit_here() , you should use t.cancel() .随后,代替end_process_and_exit_here()你应该使用t.cancel() This seems to work and stops all threads mid-process.这似乎有效并在进程中停止所有线程。 However, the bad thing is that it doesn't seem to carry on with other parts of the program.然而,不好的是它似乎并没有继续执行程序的其他部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中停止线程(我有一个无限循环) - How do I stop a Thread in Python (I have an endless loop) 如何在Python中的线程中停止for循环? - How to stop a for loop in a thread in Python? 如何在Python中停止此循环? - How do I stop this loop in Python? 如果线程 function 在 Python 结束,我该如何停止它? - How do I stop the thread function if it is ended in Python? 如何在 Tkinter GUI 中停止和重新启动 python 线程? - How do I stop and restart a python thread within Tkinter GUI? 如何在python线程中运行和停止无限循环 - How to run and stop an infinite loop in a python thread 如何在Python中的while循环内停止for循环 - How to Stop a for loop, inside of a while Loop in python python函数如何调用而不等待它完成处理,而该函数必须被调用一次。 因此,线程必须停止 - How a python function called and do not wait it finish processing meanwhile that function must be called once. So, thread must be stop 我如何访问本身是另一个字典值的列表中键的所有值? - How do i access all values of keys inside a list which itself is a value of another dictionary? 如何在Python 3中停止执行exec命令? - How do I stop execution inside exec command in Python 3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM