- 整理并发编程三天内容理论,用自己的概述
- 需要掌握如何开设进程和如何开设线程的代码
开设进程
from multiprocessing import Process
import time
import random
def task(name):
print('%s is running'%name)
time.sleep(3)
print('%s id over'%name)
if __name__ == '__main__':
p=Process(target=task,args=('jason',))
p.start()
print('这是主进程')
开设线程
from multiprocessing import Process
from threading import Thread
import time
def task(name):
print('%s is running'%name)
time.sleep(1)
print('%s is over'%name)
t=Thread(target=task,args=('egon',))
t.start()
print('这是主线程')
服务端
import socket
from multiprocessing import Process
from threading import Thread
server=socket.socket()#括号内不加参数默认是tcp协议
server.bind(('0.0.0.0',8000))
server.listen(5)
def task(conn,addr):
#通信循环
while True:
try:
data=conn.recv(1024)
if len(data) == 0:break
print('客户端地址:',addr)
conn.send(data.upper())
except ConnectionRefusedError as e:
print(e)
break
conn.close()
#链接循环
while True:
conn,addr=server.accept()
t=Thread(target=task,args=(conn,addr))
t.start()
客户端
import socket
client=socket.socket()
client.connect(('39.97.209.187',8000))
while True:
msg=input('your cmd>>:').strip()
if msg == 'q':break
client.send(msg.encode('utf-8'))
data=client.recv(1024)
print(data.decode('utf-8'))