文件名称:创建一个线程池-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:40
python cookbook 第3版 高清 中文完整版
12.7 创建一个线程池 问题 You want to create a pool of worker threads for serving clients or performing other kinds of work. 解决方案 The concurrent.futures library has a ThreadPoolExecutor class that can be used for this purpose. Here is an example of a simple TCP server that uses a thread-pool to serve clients: from socket import AF_INET, SOCK_STREAM, socket from concurrent.futures import ThreadPoolExecutor def echo_client(sock, client_addr): ‘’’ Handle a client connection ‘’’ print(‘Got connection from’, client_addr) while True: msg = sock.recv(65536) if not msg: break sock.sendall(msg) print(‘Client closed connection’) sock.close() def echo_server(addr): pool = ThreadPoolExecutor(128) sock = socket(AF_INET, SOCK_STREAM) sock.bind(addr) sock.listen(5) while True: client_sock, client_addr = sock.accept() pool.submit(echo_client, client_sock, client_addr) echo_server((‘’,15000)) If you want to manually create your own thread pool, it’s usually easy enough to do it using a Queue. Here is a slightly different, but manual implementation of the same code: from socket import socket, AF_INET, SOCK_STREAM from threading import Thread from queue import Queue def echo_client(q): ‘’’ Handle a client connection ‘’’ sock, client_addr = q.get() print(‘Got connection from’, client_addr) while True: