Python 线程库:代码线性执行而不是并行执行

Python threading library: code executes linearly and not in parallel

我想 运行 两个并行线程(在 python3.6 上),这适用于以下代码示例:

import threading
from time import sleep

# use Thread to run def in background
# Example:
def func1():
    while True:
        sleep(1)
        print("Working")

def func2():
    while True:
        sleep(2)
        print("Working2")


Thread(target = func1).start()
Thread(target = func2).start()

但它不适用于 threading.Thread:

import threading
from time import sleep
# use Thread to run def in background
# Example:
def func1():
    while True:
        sleep(1)
        print("Working")

def func2():
    while True:
        sleep(2)
        print("Working2")


x = threading.Thread(target=func1())
y = threading.Thread(target=func2())
x.start()
y.start()

我想使用后一个选项来检查 x 或 y 是否还活着。

Thread(target = func1)(第一个代码)和Thread(target=func1())(第二个代码)有区别:

  • 第一个将函数对象传递给Thread
  • 第二个执行函数(因为你func1()调用它)并传递它的return 值Thread

因为你想让线程调用你的函数,所以不要调用它们:

x = threading.Thread(target=func1)
y = threading.Thread(target=func2)
x.start()
y.start()