目的:data1+data2
data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] #向量1
data2 = [3, 4, 5, 6, 2, 4, 3, 4, 5, 7] #向量2
方法:thread[i] 执行 Q.put(data1[i]+data2[i])
源码:
# 导入包
import threading
from queue import Queue
#每一个线程都需要执行的函数,每一位的加法
def job(i, j, q):
q.put(i + j)
def multiThreadingData():
q = Queue() #队列
threads = [] #线程列表
result = [] #结果列表
data1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] #向量1
data2 = [3, 4, 5, 6, 2, 4, 3, 4, 5, 7] #向量2
for (i, j) in zip(data1, data2): #联合成元组
t = threading.Thread(target=job, args=(i, j, q)) #新建线程
threads.append(t)
t.start() #开启线程
for thread in threads:
thread.join() #阻塞直到掉用join的线程结束
for _ in range(q.qsize()):
result.append(q.get())
print(result) #打印结果
def main():
multiThreadingData()
if __name__ == '__main__':
main()
结果:
/home/hugh/miniconda3/envs/env_torch/bin/python /home/hugh/PycharmProjects/demo.py
[4, 6, 8, 10, 7, 10, 10, 12, 14, 7]
Process finished with exit code 0