gpt4 book ai didi

python - 如何使用多线程

转载 作者:太空狗 更新时间:2023-10-29 17:06:09 26 4
gpt4 key购买 nike

我有这个代码:

import thread

def print_out(m1, m2):
print m1
print m2
print "\n"

for num in range(0, 10):
thread.start_new_thread(print_out, ('a', 'b'))

我想创建10个线程,每个线程运行函数print_out,但是我失败了。错误如下:

Unhandled exception in thread started by 
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr

最佳答案

首先,您应该使用更高级别的threading 模块,特别是Thread 类。 thread 模块不是您所需要的。

当您扩展此代码时,您很可能还希望等待线程完成。以下是如何使用 join 方法实现此目的的演示:

import threading

class print_out(threading.Thread):

def __init__ (self, m1, m2):
threading.Thread.__init__(self)
self.m1 = m1
self.m2 = m2

def run(self):
print self.m1
print self.m2
print "\n"

threads = []
for num in range(0, 10):
thread = print_out('a', 'b')
thread.start()
threads.append(thread)

for thread in threads:
thread.join()

关于python - 如何使用多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9532264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com