Pool内的进程数默认是cpu核数,假设为4(查看方法os.cpu_count())
开启6个客户端,会发现2个客户端处于等待状态
在每个进程内查看pid,会发现pid使用为4个,即多个客户端公用4个进程
tcp_server.py
# -*- coding: utf-8 -*-
import os
from socket import *
from multiprocessing import Pool
def talk(conn):
while 1: # 循环通讯
try:
from_client_msg = conn.recv(1024)
if not from_client_msg:break
print("进程(%s)来自客户端的消息:%s" %(os.getpid(), from_client_msg))
conn.send(from_client_msg.upper())
except:
break
conn.close()
if __name__ == '__main__':
server = socket()
ip_port = ("127.0.0.1", 8001)
server.bind(ip_port)
server.listen(5)
pool = Pool(4) # 创建进程池,进程池内,最多可运行4个进程
while 1: # 循环连接
conn, addr = server.accept()
pool.apply_async(talk, args=(conn,)) # 异步执行
pool.close() # 进程池不再接收新任务
pool.join() # 进程池内的进程都执行完了
server.close()
# 进程(5536)来自客户端的消息:b'aa'
# 进程(4440)来自客户端的消息:b'bb'
# 进程(3268)来自客户端的消息:b'cc'
# 进程(4876)来自客户端的消息:b'dd'
# 进程(5536)来自客户端的消息:b'ee'
# 进程(4440)来自客户端的消息:b'ff'
tcp_client.py
# -*- coding: utf-8 -*-
from socket import *
client = socket()
ip_port = ("127.0.0.1", 8001)
client.connect(ip_port)
while 1: # 循环通讯
inp = input(">>:").strip()
if not inp: continue
if inp.upper() == "Q": break
client.send(inp.encode())
from_server_msg = client.recv(1024)
print("来自服务端的消息:", from_server_msg)
client.close()
# >>:cc
# 来自服务端的消息: b'CC'
# >>:
发现:并发开启多个客户端,服务端同一时间只有4个不同的pid,只能结束一个客户端,另外一个客户端才会进来.