Pool内的进程数默认是cpu核数,假设为4(查看方法os.cpu_count())开启6个客户端,会发现2个客户端处于等待状态在每个进程内查看pid,会发现pid使用为4个,即多个客户端公用4个进程tcp_server.py
# coding:utf-8 import os import socket from multiprocessing import Pool def tcpserver(conn): while 1: from_client_msg = conn.recv(1024) if not from_client_msg: break print("[%s]来自客户端的消息:" % os.getpid(), from_client_msg) conn.send(from_client_msg.upper()) if __name__ == ‘__main__‘: server = socket.socket() ip_port = ("127.0.0.1", 8001) server.bind(ip_port) server.listen(5) pool = Pool(os.cpu_count()) print("pool count:", os.cpu_count()) while 1: conn, addr = server.accept() res = pool.apply_async(tcpserver, args=(conn,)) pool.close() pool.join()
tcp_client.py
# coding:utf-8 import socket if __name__ == ‘__main__‘: client = socket.socket() ip_port = ("127.0.0.1", 8001) client.connect(ip_port) while 1: inp = input(">>>>:").strip() if not inp: continue client.send(inp.encode("utf-8")) from_server_msg = client.recv(1024) print("来自服务端的消息:", from_server_msg)
发现:并发开启多个客户端,服务端同一时间只有4个不同的pid,只能结束一个客户端,另外一个客户端才会进来.
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10986698.html
时间: 2024-11-10 00:39:19