pythonマルチスレッドの戻り値の取得

2938 ワード

ネットワークから転載https://www.cnblogs.com/hujq1029/p/7219163.html爬虫類を併発する場合に使用
import threading


class MyThread(threading.Thread):

    def __init__(self,func,args=()):
        super(MyThread,self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  #         join  ,        self.result   
        except Exception:
            return None


def foo(a,b,c):
    time.sleep(1)
    return a*2,b*2,c*2

st = time.time()
li = []
for i in xrange(4):
    t = MyThread(foo,args=(i,i+1,i+2))
    li.append(t)
    t.start()

for t in li:
    t.join()  #    join,            ,      
    print t.get_result()

et = time.time()
print et - st
    :
(0, 2, 4)
(2, 4, 6)
(4, 6, 8)
(6, 8, 10)
1.00099992752