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

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

最佳答案

推荐的方法是使用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/

相关文章:

python - 有没有一种优雅的方法来使用 struct 和 namedtuple 而不是这个?

Python:如何在两列之间的 Pandas 数据框中添加一列?

java - 如何确保文件仅由 Java 中的多线程从磁盘加载一次

python - 具有可变索引的多线程应用程序中的异步文件IO

python - 在 python 中跳过 quandl 的 ssl 验证

python - 将 pandas 数据框中列的超出定义间隔限制的值设置为给定值(例如 NaN)

python - 如何将带有表情符号名称的字符串转换为不和谐的表情符号?

python - 循环识别素数和非素数生成错误输出

python - 如何 for 循环遍历两个嵌套循环内的字符串列表并避免外部循环造成的冗余?

java - 使用spring任务调度处理多个文件时如何保持一致性?