在单独的python线程中运行函数

时间:2020-08-07 00:53:04

标签: python python-3.x multithreading

(Python 3.8.3)

我现在正在使用两个python线程,其中一个线程有一个True循环

import threading
def threadOne():
    while True:
        do(thing)
    print('loop ended!')
t1=threading.Thread(threadOne)
t1.start()

另一个检查ctrl + r输入。收到后,我需要第二个线程告诉第一个线程从while循环中断。有办法吗?

请注意,我无法将循环更改为“ while Break == False”,因为do(thing)等待用户输入,但是我需要将此循环中断。

1 个答案:

答案 0 :(得分:2)

推荐的方法是使用threading.event(如果您也想在该线程中睡眠,则可以将它与event.wait结合使用,但是在等待用户事件时,可能不需要)。

import threading

e = threading.Event()
def thread_one():
    while True:
        if e.is_set():
            break
        print("do something")
    print('loop ended!')

t1=threading.Thread(target=thread_one)
t1.start()
# and in other thread:
import time
time.sleep(0.0001)  # just to show thread_one keeps printing
                    # do something for little bit and then it break
e.set()

编辑:要在线程等待用户输入时中断线程,您可以将SIGINT发送到该线程,它将引发KeyboardInterrupt,您可以随后对其进行处理。 python(包括python3)的不幸局限在于,所有线程的信号都在主线程中处理,因此您需要等待用户在主线程中输入:

import threading
import sys
import os
import signal
import time

def thread_one():
    time.sleep(10)
    os.kill(os.getpid(), signal.SIGINT)

t1=threading.Thread(target=thread_one)
t1.start()

while True:
    try:
        print("waiting: ")
        sys.stdin.readline()
    except KeyboardInterrupt:
        break
print("loop ended")