python - Python 3.4 中多线程如何工作?

标签 python multithreading python-multithreading

我只是在玩多线程,但我似乎无法让它工作。我看过其他问题,但没有一个真正对我有帮助。到目前为止,这是我的代码:

import threading, time

def hello():
    for i in range(1,5):
        time.sleep(1)
        print("Hello")

def world():
    for i in range(1,5):
        time.sleep(1)
        print("World")

newthread = threading.Thread(hello())
newthread.daemon = True
newthread.start()
otherthread = threading.Thread(world())
otherthread.daemon = True
otherthread.start()
print("end")

我希望得到类似的东西:

Hello
World
Hello
World
Hello
World
Hello
World
end

但我得到的是:

Hello
Hello
Hello
Hello
World
World
World
World
end

最佳答案

threading.Thread(hello())

您调用了函数 hello 并将结果传递给 Thread,因此它在线程对象存在之前就执行了。传递普通函数对象:

threading.Thread(target=hello)

现在线程将负责执行该函数。

关于python - Python 3.4 中多线程如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37689138/

相关文章:

c++ - 用 Poco :Condition 唤醒两个线程

Java单线程多用户聊天程序

python - 运行时警告 : coroutine was never awaited self. _target(*self._args, **self._kwargs)

Python Asyncio错误: "OSError: [WinError 6] The handle is invalid" and "RuntimeError: Event loop is closed"

python - 如何传递 python 脚本作为参数?

python - Tkinter 键盘绑定(bind)

python - 运行 Nose 测试时出错

ios - 如何等待 NSURLConnection 委托(delegate)完成后再继续?

python - Django-haystack 搜索#hashtag

process - Keras "pickle_safe": What does it mean to be "pickle safe", 或者 Python 中的 "non picklable"?