程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Multi way driving -- Realizing Python multithreading and multithreading to obtain return value by specifying the number of threads

編輯:Python

# coding=utf-8
import threading, time


# 1、 Write your own code , Using global variables to save thread execution results


 

def get_detail_video(vid):
    print('-->', vid)
    time.sleep(2)
datas = []
ths = []
for i in range(10):
    th = threading.Thread(target=get_detail_video, args=(i, datas,))
    th.start()
    ths.append(th)
    if len(ths) >= 3:
        for t in ths:
            t.join()
        ths.clear()
for t in ths:
    t.join()



# 2、 Rewrite Module , Get the execution result of each thread directly

# coding=utf-8
from threading import Thread
import time
class MyThread(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
except Exception:
return None
def a(x, y):
time.sleep(2)
return x+y
def b(x, y):
time.sleep(2)
return x+y
at = []
t1 = MyThread(a, args=(1,2,))
at.append(t1)
t2 = MyThread(b, args=(10,20,))
at.append(t2)
print(len(at))
ss_tt = time.time()
for t in range(len(at)):
aa = at[t]
aa.start()
for t in at:
t.join()
r1 = t1.get_result()
print(' MyThread__%s Time consuming : %s, result = %s' % (1, time.time() - ss_tt, r1))
r2 = t2.get_result()
print(' MyThread__%s Time consuming : %s, result = %s' % (2, time.time() - ss_tt, r2))
ss_tt = time.time()
r1 = a(1,2)
print(' MyThread__%s Time consuming : %s, result = %s' % (1, time.time() - ss_tt, r1))
r2 = b(10,20)
print(' MyThread__%s Time consuming : %s, result = %s' % (2, time.time() - ss_tt, r2))



# 3、 Using thread pools modular

import threadpool
excel_datas = [1, 2, 3]
def run_xhs(i):
return i
#  Callback function , Accepted parameters ( Request itself , And request work function execution results ) It can be omitted   
spider_results = []
def get_result(tt_requests, result):
global spider_results
spider_results.append(result)
tt_pool = threadpool.ThreadPool(2) # The specified number of threads is 2
tt_requests = threadpool.makeRequests(run_xhs, excel_datas, get_result) # Function name , list
for tt_req in tt_requests:
tt_pool.putRequest(tt_req)
tt_pool.wait()
if spider_results:
print('spider_results = ', len(spider_results))
write_excel_data(spider_results, excel_name)
# spider_results = 3 [1, 2, 3]
 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved