【问题标题】:Python multithreading from multiple files来自多个文件的 Python 多线程
【发布时间】:2015-01-10 18:45:08
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.x python-multithreading


    【解决方案1】:

    将所有行放在background.py 中的for 循环之前。当它被导入时,它将启动线程运行。更改 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
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多