如何使用多个线程

Sea*_*ene 15 python multithreading

我有这个代码:

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'))
Run Code Online (Sandbox Code Playgroud)

我想创建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
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 13

首先,您应该使用更高级别的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()
Run Code Online (Sandbox Code Playgroud)