一:进程之间的内存空间是共享的还是隔离的?下述代码的执行结果是什么?
结果:
主进程:100
子进程:0
进程之间的内存空间是隔离的。
from multiprocessing import Process n=100 #在windows系统中应该把全局变量定义在if __name__ == '__main__'之上就可以了 def work(): global n n=0 print('子进程内: ',n) if __name__ == '__main__': p=Process(target=work) p.start() p.join() print('主进程内: ',n)
二:基于多进程实现并发的套接字通信?
服务端
from socket import * from multiprocessing import Process class Server: code = 'utf-8' family_net = AF_INET type_net = SOCK_STREAM request_queue_size = 5 max_packet_size = 1024 def __init__(self, server_address): self.server_address = server_address self.socket = socket(self.family_net, self.type_net) try: self.server_bind() self.server_listen() except: self.server_close() raise def server_bind(self): self.socket.bind(self.server_address) def server_listen(self): self.socket.listen(self.request_queue_size) def server_close(self): self.socket.close() def run(self): while True: print('waiting...') self.conn, self.addr = self.socket.accept() p = Process(target=self.sub_p,) p.start() def sub_p(self): while True: ret = self.conn.recv(self.max_packet_size).decode(self.code) if not ret: break ret_bytes = ret.upper().encode(self.code) self.conn.send(ret_bytes) if __name__ == '__main__': s = Server(('127.0.0.1', 8099)) s.run()
客户端
from socket import * class Client: code = 'utf-8' family_net = AF_INET type_net = SOCK_STREAM max_packet_size = 1024 def __init__(self, server_address): self.server_address = server_address self.socket = socket(self.family_net, self.type_net) try: self.client_connect() except: self.clent_close() raise def client_connect(self): self.socket.connect(self.server_address) def clent_close(self): self.socket.close() def run(self): while 1: ret = input('>>>').strip() if not ret: break self.socket.send(ret.encode(self.code)) data = self.socket.recv(self.max_packet_size) print(data.decode(self.code)) if __name__ == '__main__': c = Client(('127.0.0.1', 8099)) c.run()