python - python 中的多线程未按预期工作

标签 python multithreading

import threading
import time

def test1():
 print "hello"
 time.sleep(15)
 print "hello2" 

def test2():
 print "hi"

th1 =threading.Thread(test1())
th2 =threading.Thread(test2())

p=[th1,th2]
for i in p:
 i.start()

for i in p:
 i.join()

不知道我说得对不对,如果不对请指正。我希望输出按照 hello hi 和 hello2 的顺序打印。因为我期望创建的两个线程并行运行。但我得到以下输出,hello hello2 和 hi。线程 2 仅在线程 1 完成后才运行。我做错了什么吗?还是我的理解或线程错误?

最佳答案

您需要将函数引用传递给 Thread() 类构造函数,该构造函数采用名为 target 的“关键字参数”(默认值:None )。

传递函数调用的结果(例如您所做的)将会产生不良行为,特别是因为 Thread() 的第一个参数实际上是 组=无

示例:(已更正)

import threading
import time


def test1():
    print "hello"
    time.sleep(15)
    print "hello2"


def test2():
    print "hi"

th1 = threading.Thread(target=test1)
th2 = threading.Thread(target=test2)

p = [th1, th2]
for i in p:
    i.start()

for i in p:
    i.join()

输出:

$ python foo.py
hello
hi
# 15s delay
hello2

参见:threading.Thread()

具体:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments.

关于python - python 中的多线程未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30229706/

相关文章:

python-3.x - 一旦主循环启动,PyStray 就会停止工作(分离模式)

c - Pthread 奇怪的行为和段错误

python - 通过 python 进行多人游戏

Python 3.2 : cx_freeze compiles my program, 但处于 Debug模式

python - 从正在运行的线程调用其他线程上的协程

c++ - 通过线程句柄获取线程的 TIB/TEB (2015)

java - 在 Android 中,如何让 Activity 在跳到下一个 Activity 之前等待?

python - 如何从标准输入等流中创建 rx.py Observable?

python - django filter_horizo​​ntal无法显示

multithreading - MPI + 线程并行化与仅 MPI 相比有什么优势(如果有)?