并行需要多个cpu才能实现并行
一个cpu只能做到并发,多个cpu同时运行多个程序实现并行。
2个cpu开启两个进程:
# -*- coding: utf-8 -*- import multiprocessing import time def now_time(): return time.asctime(time.localtime(time.time())) # process one def run(): # 并行是模拟耗时任务,并发是模拟阻塞 !! print('one start:', now_time()) time.sleep(5) print('one end:', now_time()) if __name__ == '__main__': process = multiprocessing.Process(target=run) process.start() # process two print('two start:', now_time()) time.sleep(5) print('two end:', now_time())
two start: Thu Mar 28 15:45:14 2019 one start: Thu Mar 28 15:45:14 2019 two end: Thu Mar 28 15:45:15 2019 one end: Thu Mar 28 15:45:19 2019
多进程实现并行
# -*- coding: utf-8 -*- ''' 多进程实现并发''' import socket import multiprocessing server = socket.socket() server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 释放端口 server.bind(('', 8888)) server.listen(1000) # 生成监听套接字 def server_recv(conn): while True: recv_data = conn.recv(1024) if recv_data: print(recv_data.decode()) conn.send(recv_data) else: conn.close() break while True: conn, addr = server.accept() # 生成对等套接字 # 将阻塞的对等套接字存入进程 process = multiprocessing.Process(target=server_recv, args=(conn, ), daemon=True) process.start()