首页 > 解决方案 > 如何在 Python 中与线程并行运行两个函数?

问题描述

我想并行运行两个函数,它们并行打印两个列表。但我得到的是一个列表,在另一个列表完成后打印。

我已经尝试了以下代码。

import threading
import time

def fun1():
    testz=['z','y','x','w','v','u','t']
    for j in testz:
        print (j)
        time.sleep(1)

def fun2():
    test=['a','b','c','d','e','f','g']
    for i in test:
        print (i)
        time.sleep(1)


thread1 = threading.Thread(target=fun1())
thread2 = threading.Thread(target=fun2())

thread1.start()
time.sleep(0.5)
thread2.start()

thread1.join()
thread2.join()

我期望的结果是:

z
a
y
b
x
c
w
d
v
e
u
f
t
g

但我得到的是:

z
y
x
w
v
u
t
a
b
c
d
e
f
g

这似乎两个线程一个接一个地运行。

标签: pythonmultithreadingfunction

解决方案


问题是您在主线程中运行函数,而不是在子线程中。您首先调用函数,然后将返回的值作为线程目标。您的代码应该是:

thread1 = threading.Thread(target=fun1)
thread2 = threading.Thread(target=fun2)

然后你会得到预期的结果。


推荐阅读