1. Thread Sharing variables
Multithreading differs from multiple processes in that multithreading itself can share memory with the parent thread, which is why one thread hangs out and why other threads die.
Import Threadingdef Worker (L): l.append ("Li") l.append ("and") L.append ("Lou") if __name__ = = "__main__": l = [] L + = range (1, ten) print (l) t = Threading. Thread (Target=worker, args= (L,)) T.start () print (L)
return Result:
[1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 5, 6, 7, 8, 9, ' Li ', ' and ', ' Lou ']
2. Thread pool (expand content, understand)
Multiple threads are implemented by passing in a parameter group, and its multithreading is ordered, and the order of the parameters in the parameter group is consistent.
Installation package:
Pip Install ThreadPool
Call Format:
From threadpool Import *pool = Treadpool (poolsize) Requests = Makerequests (some_callable, List_of_args, callback) [ Pool.putrequest (req) for req in requests]pool.wait ()
Example:
Import threadpooldef hello (M, n, o): print ("m = {0} , n = {1}, o = {2} ". Format (M, n, o)) if __name__ == " __ main__ ": #方法一: lst_vars_1 = [' 1 ', ' 2 ', ' 3 '] lst_vars_2 = [' 4 ', ' 5 ', ' 6 '] func_var = [(lst_vars_1,None ), (Lst_vars_2, none)] #方法二: dict_vars_1 = { ' m ': ' 1 ', ' n ': ' 2 ', ' O ': ' 3 '} dict_vars_2 = {' m ': ' 4 ', ' N ': ' 5 ', ' O ': ' 6 '} func_var = [(none, dict_vars_1), (none, dict_vars_2)] pool = threadpool. ThreadPool (2) requests = threadpool.makerequests (Hello, func_var) [pool.putrequest (req) for req in requests] pool.wait ()
return Result:
m = 1, n = 2, o = 3m = 4, n = 5, o = 6
+ Python multi-threaded shared variable thread pool