python中的多執行緒threading之儲存程序結果Queue
阿新 • • 發佈:2018-11-14
程式碼實現功能,將資料列表中的資料傳入,使用四個執行緒處理,將結果儲存在Queue中,執行緒執行完後,從Queue中獲取儲存的結果
import threading
from queue import Queue
def job(l, q):
for i in range(len(l)):
l[i] = l[i] ** 2
q.put(l)
def multithreading():
q = Queue()
threads = []
data = [[1, 2, 3], [3, 4, 5], [7, 8, 9], [ 5, 5, 5]]
for i in range(4):
t = threading.Thread(target=job, args=(data[i], q))
t.start()
threads.append(t)
for thread in threads:
thread.join()
results = []
for _ in range(4):
results.append(q.get())
print(results)
def main():
multithreading( )
if __name__ == '__main__':
main()