【问题标题】:Python threading library: code executes linearly and not in parallelPython线程库:代码线性执行而不是并行执行
【发布时间】:2021-10-16 16:21:21
【问题描述】:

我想并行运行两个线程(在 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()

但它不适用于线程。线程:

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 是否还活着。

【问题讨论】:

    标签: python python-3.x multiprocessing python-multithreading


    【解决方案1】:

    Thread(target = func1)(第一个代码)和Thread(target=func1())(第二个代码)之间存在区别:

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

    由于您希望 线程 调用您的函数,因此不要调用它们:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多