4.24作业

from multiprocessing import Process
import time
import random

def task(n):
time.sleep(random.randint(1,3))
print('------->%s' %n)

if __name__ == '__main__':
p1 = Process(target=task,args=(1,))
p2 = Process(target=task,args=(2,))
p3 = Process(target=task,args=(3,))

p1.start()
p2.start()
p3.start()
print('----------->4')


效果1:最先输出---------->4并发
   p1.start()
p2.start()
p3.start()
print('----------->4')

效果2:最后输出---------->4并发
#     p1.start()
# p2.start()
# p3.start()
# p1.join()
# p2.join()
# p3.join()
#
# print('----------->4')

效果3:顺序输出-------串行
#
# p1.start()
# p1.join()
# p2.start()
# p2.join()
# p3.start()
# p3.join()
#
# print('----------->4')



套接字实现并发
有问题存在: 不能无线并发,pid数目是有限的,不能无限并发
from socket import *
from multiprocessing import Process

server=socket(AF_INET,SOCK_STREAM)
server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
server.bind(('127.0.0.1',8080))
server.listen(5)

def talk(conn,client_addr):
    while True:
        try:
            msg=conn.recv(1024)
            if not msg:break
            conn.send(msg.upper())
        except Exception:
            break

if __name__ == '__main__': #windows下start进程一定要写到这下面
    while True:
        conn,client_addr=server.accept()
        p=Process(target=talk,args=(conn,client_addr))
        p.start()
服务端
from socket import *

client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))


while True:
    msg=input('>>: ').strip()
    if not msg:continue

    client.send(msg.encode('utf-8'))
    msg=client.recv(1024)
    print(msg.decode('utf-8'))
客户端

 




posted @ 2018-04-24 18:33  木夂口  阅读(130)  评论(0编辑  收藏  举报
levels of contents