Python 3.4 中的多线程如何工作?
How does multi-threading work in Python 3.4?
我只是在玩弄多线程,但我似乎无法让它工作。我看过其他问题,但 none 确实帮助了我。到目前为止,这是我的代码:
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)
现在 Thread
将负责执行函数。
你想要这样的东西:
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(target=hello)
newthread.start()
otherthread = threading.Thread(target=world)
otherthread.start()
# Just for clarity
newthread.join()
otherthread.join()
print("end")
连接告诉主线程在退出前等待其他线程。如果你想让主线程不等待就退出,设置[=12=],不要加入。输出可能会让您有点吃惊,它并不像您预期的那样干净。例如我得到这个输出:
HelloWorld
World
Hello
World
Hello
WorldHello
我只是在玩弄多线程,但我似乎无法让它工作。我看过其他问题,但 none 确实帮助了我。到目前为止,这是我的代码:
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)
现在 Thread
将负责执行函数。
你想要这样的东西:
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(target=hello)
newthread.start()
otherthread = threading.Thread(target=world)
otherthread.start()
# Just for clarity
newthread.join()
otherthread.join()
print("end")
连接告诉主线程在退出前等待其他线程。如果你想让主线程不等待就退出,设置[=12=],不要加入。输出可能会让您有点吃惊,它并不像您预期的那样干净。例如我得到这个输出:
HelloWorld
World
Hello
World
Hello
WorldHello