如何使用多线程 [英] How to use multiple threads
本文介绍了如何使用多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
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
,但是我失败了.错误如下:
I want to create 10 threads, each thread runs the function print_out
, but I failed. The errors are as follows:
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
模块不是您所需要的.
First of all, you should use the higher level threading
module and specifically the Thread
class. The thread
module is not what you need.
在扩展此代码时,您很可能还希望等待线程完成.以下是如何使用join
方法实现此目的的演示:
As you extend this code, you most likely will also want to wait for the threads to finish. Following is a demonstration of how to use the join
method to achieve that:
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()
这篇关于如何使用多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文