Multithreading - Queue (store process results)

1. The functions implemented

The results code to achieve the function, the list of incoming data, using four-threaded processing, the result is stored in the Queue, the thread after the implementation, to obtain storage from the Queue

2. Import thread queue standard modules

import threading
import time
from queue import Queue

3. Define a function to be called multiple threads

Is a list of function parameters l and a queue q, function is the function for each element of the list is squared, the result will be stored in the queue

def job(l,q):		#定义线程需要干的工作(q是要存放计算结果的)
    for i in range (len(l)):
        l[i] = l[i]**2
    q.put(l)   #多线程调用的函数不能用return返回值

4. Define a function multithreaded

In a multi-thread function defined Queue for return value, instead of the return, the definition of a list of multi-threaded, multi-dimensional data to initialize a list for processing:
define four threads in a multithreading functions, start threads, each Add to the list of threads in multi-threaded

def multithreading():
    q = Queue()         #实例化Queue(),在q里面放入job的返回值来替代return这个功能
    threads = []          #把所有的线程放入threads列表中
    data = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    for i in range(4):			#定义四个线程
        t = threading.Thread(target=job,args=(data[i],q)##Thread首字母要大写,被调用的job函数没有括号,只是一个索引,参数在后面
        t.start()
        threads.append(t)	##把每个线程append到线程列表中

Respectively join four threads to the main thread

 for thread in threads:
        thread.join()

The results define an empty list of results, the four lines stored in the queue after the operation is returned to the empty list results

results = []
for _ in range(4):
    results.append(q.get())  #q.get()按顺序从q中拿出一个值
print(results)

The complete code

import threading
import time
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()         #实例化Queue(),在q里面放入job的返回值来替代return这个功能
    threads = []          #把所有的线程放入threads列表中
    data = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    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)
Published 106 original articles · won praise 296 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/104731890