Python 来自多个文件的多线程

Python multithreading from multiple files

这是我想如何使用线程的示例演示。

import threading
import time

def run():
    print("started")
    time.sleep(5)
    print("ended")


thread = threading.Thread(target=run)
thread.start()

for i in range(4):
    print("middle")
    time.sleep(1)

如何从多个文件制作这个线程工作演示?

示例:

# Main.py 
import background

""" Here I will have a main program and \
I want the command from the background file to constantly run. \
Not just once at the start of the program """

第二个文件:

# background.py

while True:
    print("This text should always be printing \
        even when my code in the main function is running")

for 循环之前的所有行放在 background.py 中。当它被导入时,它将启动线程 运行。更改 run 方法来执行无限 while 循环。

您可能还想在启动线程时设置 daemon=True,以便在主程序退出时退出。

main.py

import time
import background
for i in range(4):
    print("middle")
    time.sleep(1)

background.py

import threading
import time

def run():
    while True:
        print("background")
        time.sleep(.5)

thread = threading.Thread(target=run,daemon=True)
thread.start()

输出

background
middle
background
middle
background
background
background
middle
background
background
middle
background
background