Introduction to Python Basics (18): The use of thread pools

Python tutorial video for beginners to watch online for free

https://space.bilibili.com/3461579964156657

Use of thread pool

ThreadPoolExecutor

There is an easier way to start a set of threads than what you saw above. It's called a ThreadPoolExecutor and it's part of the standard library concurrent.futures (starting with Python 3.2).

The easiest way to create it is as a context manager, using the with statement to manage pool creation and destruction.

import concurrent.futures
import time
 
def thread_function(name) :
    print("子线程%s:启动”% name)
    time.s1eep(2)
    print("子线程%s:完成”% name)
if __name__ == "_main__":
    with concurrent.futures.ThreadPoo1Executor(max_workers=3) as executor":
    for i in range(10):
        executor.submit(thread_function,i)

The code creates a ThreadPoo1Executor context manager, telling it how many worker threads it wants in the pool. It then .map()s through the iterable of things, in your case range(3), passing each thing to a thread in the pool.

The end of the with block causes a ThreadPoo7Executor to execute a .join()) on each thread in the pool. It is strongly recommended that you use the ThreadPoo1Executor context manager so that you never forget to .join() threads.

The sample code will generate output that looks like this:

子线程0:启动
子线程1:启动
子线程2:启动
子线程2:完成
子线程0:完成
子线程1:完成

Advantages and disadvantages of multithreading

advantage:

  • Multi-threading technology makes the program respond faster and allows the program to execute efficiently
  • Increased computing power

shortcoming:

  • Multithreading has no absolute order of execution (understanding)

  • Waiting to use shared resources causes the program to run slower. These shared resources are mainly exclusive resources, such as global variables.

  • Managing threads requires additional CPU overhead. The use of threads imposes an additional burden on the system for context switching. When this burden exceeds a certain level, the characteristics of multithreading are mainly manifested in its shortcomings, such as using independent threads to update each element in the array.

  • Thread deadlock. That is, multithreading symptoms such as long waits or resource competition and deadlocks.

Python answer exchange, case source code sharing

Guess you like

Origin blog.csdn.net/Dangerous_li/article/details/127639271