2012-03-02 98 views
15

我有这样的代码:如何使用多线程

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 

回答

12

首先,你应该使用更高级别的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() 
+0

'thread.join()'用于等待线程终止。我注意到如果我不添加最后两行代码:'对于线程中的线程:thread.join()',程序也运行良好,并且每个线程都根据调试在'thread.start()'执行,IOW如果我不添加'time.time(0.1)',我不需要添加代码'thread.join()',因为程序会自动等待线程在'thread.start()'完成任务,对吧? – Searene 2012-03-02 11:34:10

+0

@Mark您根本不需要添加'time.sleep(0.1)'。这没有必要。是的,您可以删除调用“join”的代码,Python环境将在终止执行之前等待所有线程完成。但是,我将这些调用添加到'join'中,因为我期望在将来的某个时刻,您需要知道如何等待线程完成其执行。但是,是的,您可以在这个简单的示例中简单地省略那些对“join”的调用。 – 2012-03-02 11:47:27

2

你应该让主线程活路了一小会儿。如果主线程死了,所有其他线程也会死掉,因此你将看不到任何输出。尝试在代码的末尾添加time.sleep(0.1),然后您将看到输出。

之后,您可以看看thread.join()以了解更多信息。

2

另一种方法是使用线程类。

instance[num]=threading.Thread(target=print_out, args=('a', 'b')) 

instance[num].start()