Import Threadpool,os #threadpool需要pip安装
def foo (i):
Print ("Son process%d%s"% (I,os.getpid ()))
return I
def back (Req,a): #俩个参数, one is the return value of the Run function foo, and the input request object will be an error
Print (a)
If __name__== "__main__":
Pool=threadpool. ThreadPool (5) #实例化空壳线程
Lst=list (I for I in range (20))
Reqs=threadpool.makerequests (Foo,lst,back) #传入参数lst需要是一个集合列表, compared to multiple processes, no need to iterate
For req in reqs:
Pool.putrequest (req) #将request对象传入线程池
Pool.wait () #相当于join ()
Print ("End")
Compared to the multiprocessing module implementation of the multi-process pool, threadpool at the time of the instantiation of a large change, three interfaces: Incoming method, passed in parameters, the callback function has changed (the thread pool is not an instantiation thread here, but a collection of requests objects is instantiated.) The process pool then instantiates the thread at the time of this parameter transfer.
As you can see, the incoming method and the incoming function have canceled the keyword func and args, we fill in the incoming object name directly, and secondly, the incoming parameter becomes a collection form. In the process pool, we iterate over each thread by passing in different parameters (just passing in the simple i+=1)
callback function back requires two incoming parameters one is the requests object, the other is the thread method return value, the line Chengjo is no return value, or none. If this is a process pool, simply accept the return value. So be sure to pay attention to passing in a requests object, otherwise it will be an error.
Steps for the entire instance thread:
The requests object is created through Thread.makerequests () because the incoming parameter is a collection, so the requests created is also a collection form, which, through an iteration, runs the objects in the requests collection through the putrequest into the thread pool, without this step being similar to the process
The Apply_async () in the pool and start () in the multi-process.
Multithreading through ThreadPool