如何理解接口幂等性
412
2022-08-27
Python从门到精通(六):线程-02-线程池(线程池 Python)
一、ThreadPoolExecutor
1.1、基本实现
from socket import AF_INET, SOCK_STREAM, socketfrom concurrent.futures import ThreadPoolExecutordef echo_client(sock, client_addr): ''' Handle a client connection ''' print(f'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))
1.2、带返回值的线程
from concurrent.futures import ThreadPoolExecutorimport requestsdef fetch_url(url): u = requests.get(url) data = u.text return datapool = ThreadPoolExecutor(10)a = pool.submit(fetch_url, '= pool.submit(fetch_url, '= a.result()y = b.result()print(x)
1.3、有限线程池
from threading import Threadfrom socket import socket, AF_INET, SOCK_STREAMdef echo_client(sock, client_addr): ''' Handle a client connection ''' print(f'Got connection from {client_addr}') while True: # msg = sock.recv(65536) if not (msg := sock.recv(65536)): break sock.sendall(msg) print('Client closed connection') sock.close()def echo_server(addr): sock = socket(AF_INET, SOCK_STREAM) sock.bind(addr) sock.listen(5) while True: client_sock, client_addr = sock.accept() t = Thread(target=echo_client, args=(client_sock, client_addr)) t.daemon = True t.start()echo_server(('',15000))
1.4、手动创建线程池
from socket import socket, AF_INET, SOCK_STREAMfrom threading import Threadfrom queue import Queuedef echo_client(q): ''' Handle a client connection ''' sock, client_addr = q.get() print(f'Got connection from {client_addr}') while True: # msg = sock.recv(65536) if not (msg := sock.recv(65536)): break sock.sendall(msg) print('Client closed connection') sock.close()def echo_server(addr, nworkers): q = Queue() for n in range(nworkers): t = Thread(target=echo_client, args=(q,)) t.daemon = True t.start() sock = socket(AF_INET, SOCK_STREAM) sock.bind(addr) sock.listen(5) while True: client_sock, client_addr = sock.accept() q.put((client_sock, client_addr))echo_server(('',15000), 128)
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~