Get the App
SLTechnology News&Howtos  ›  Development  › 

How to operate multithreaded by Python

Shulou Source: shulou.com Published: 2022-06-01 13:19:59 10月07日 Update

This article mainly explains "how Python performs multithreaded operation". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it slowly to study and learn "how Python performs multithreaded operation" together.

1. Thread pool module

introduced

from concurrent.futures import ThreadPoolExecutor2, Use thread pool

A simple thread pool use case

from concurrent.futures import ThreadPoolExecutorimport timepool = ThreadPoolExecutor(10, 'Python')def fun(): time.sleep(1) print(1, end='')if __name__ == '__main__': #List derivations [pool.submit(fun) for i in range(20) if True]from concurrent.futures import ThreadPoolExecutorimport timepool = ThreadPoolExecutor(10, 'Python')def fun(arg1,arg2): time.sleep(1) print(arg1, end=' ') print(arg2, end=' ')if __name__ == '__main__': #List derivations [pool.submit(fun,i,i) for i in range(20) if True] #Execution of a single thread task = pool.submit(fun,'Hello','world') #Judge task execution status print(f'task status {task.done()}') time.sleep(4) print(f'task status {task.done()}') #The function that gets the result is blocking, so it will wait until the thread ends before outputting print(task.result())3, Get the result

blocking wait

print(task.result())

Get results in batches

for future in as_completed(all_task): data = future.result()

Block the main thread, waiting for execution to end before executing the next transaction

#Wait for all threads to finish executing wait(pool.submit(fun,1,2),return_when=ALL_COMPLETED)print ('') Thank you for reading, the above is the content of "Python how to multithread operation", after learning this article, I believe that everyone has a deeper understanding of how Python performs multithreaded operation, and the specific use needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Threads results learning blocking content business tasks functions single that is ideas situations articles more cases modules states knowledge knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MariaDB NVidia macOS Shulou Tech Info