+ Python multi-threaded shared variable thread pool

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.