gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:23:24 38 4
gpt4 key购买 nike

(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)等待用户输入,但是我需要将其中断。

最佳答案

推荐的方法是使用threading.event(如果您也想在该线程中 sleep ,则可以将其与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")

关于python - 在单独的python线程中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63293718/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com