Case: Squaring of nested list elements
Recently, I have been learning the application of multi-threading and queues. I have read many texts and coursewares of queues and multi-threads before, but I can't write such cases. Later, after meeting the actual needs of the project, referring to the case, I have a better understanding of the application of queues and multiple components.
The value of the calculation of each thread of the multi-thread is put in a queue, and then taken out when the main thread is used instead.
Direct case:
# queue 多线程各个线程的运算的值放到一个队列中,到主线程的时候再拿出来,以此来代替
# return的功能,因为在线程是不能返回一个值
import time
import threading
from queue import Queue
def job(l, q):
print ("AA",l) #传入列表中元素(第一次[1, 2, 3]
print("BB", q) #传入队列方法地址,暂理解为内存地址,方便计算
q.put([i ** 2 for i in l]) ##从列表中取出单个数据进行平方运算。注意队列方法PUT(传入)
## 例如第一个列表[1, 2, 3]中的1,2,3
##借此可以替换自己的函数
def multithreading(data):
print (data) ##传入要执行运算的整体列表……
q = Queue() ##队列实例化
threads = [] ##多线程任务初始化
for i in range(len(data)):
print ("DATE_A",data[i]) #遍历整体列表中的元素,准备带入队列和多线程。
t = threading.Thread(target=job, args=(data[i], q)) #多线程传参,
t.start() ##多线程执行。
threads.append(t) #组成多线程任务列表
for thread in threads:
thread.join()
results = []
for _ in range(len(data)):
results.append(q.get()) ##遍历取出执行结果,追加到新列表。注意队列GET方法,取出结果
print (results)
if __name__ == "__main__":
data = [[1, 2, 3], [4, 5, 6], [3, 4, 3], [5, 5, 5]]
multithreading(data)
The results are as follows:
[[1, 2, 3], [4, 5, 6], [3, 4, 3], [5, 5, 5]]
data [1, 2, 3]
AA [1, 2, 3]
data [4, 5, 6]
BB <queue.Queue object at 0x7f35d9935f98>
AA [4, 5, 6]
data [3, 4, 3]
BB <queue.Queue object at 0x7f35d9935f98>
AA [3, 4, 3]
data [5, 5, 5]
BB <queue.Queue object at 0x7f35d9935f98>
AA [5, 5, 5]
BB <queue.Queue object at 0x7f35d9935f98>
[[1, 4, 9], [16, 25, 36], [9, 16, 9], [25, 25, 25]]
More easy-to-understand case references:
https://www.runoob.com/python3/python3-multithreading.html