简体   繁体   中英

Run a function in a seperate python thread

(Python 3.8.3)

I am using two python threads right now, one that has a while True loop

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

And another that checks for a ctrl+r input. When recieved, I need the second thread to tell the first thread to break from the while loop. Is there a way to do this?

Note that I cannot change the loop to 'while Break == False' as do(thing) waits for user input, but i need this to be interrupted.

The recommended way is to use threading.event (You can combine this with event.wait if you want to sleep in that thread too however as you are waiting for a user event, probably dont need that).

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()

EDIT: To interrupt the thread while it's waiting for user input you can send SIGINT to that thread and and it will raise KeyboardInterrupt which you can then handle. Unfortunate limitation of python, including python3, is that signals to all threads are handled in the main thread so you need to wait for the user input in the main thread:

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM