一 threading模块介绍
multiprocess模块完全模仿了threading模块的接口,二者在使用层面,有很大的相似性
二 开启线程的两种方式
方式一
from threading import Thread
import time
def sayhi(name):
time.sleep(2)
print("%s say hello" % name)
if __name__ == '__main__':
t = Thread(target=sayhi, args=('mike', ))
t.start()
print("主线程")
方式二
from threading import Thread
import time
class Sayhi(Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
time.sleep(2)
print('%s say hello' % self.name)
if __name__ == '__main__':
t = Sayhi('mike')
t.start()
print("主线程")
三 练习题
1、基于多线程实现并发的套接字通信
客户端:
from socket import *
ip = '127.0.0.1'
port = 8081
c = socket(AF_INET, SOCK_STREAM)
c.connect((ip, port))
while True:
msg = input("请输入客户端的信息").strip()
if not msg:
continue
c.send(msg.encode('utf-8'))
data = c.recv(1024)
print("收到的信息:", data.decode('utf-8'))
服务端:
from socket import *
from threading import Thread
def talk(conn):
while True:
try:
data = conn.recv(1204)
if not data:
break
conn.send(data.upper())
except ConnectionResetError:
break
conn.close()
def server(ip, port):
server_socket = socket(AF_INET, SOCK_STREAM)
server_socket.bind((ip, port))
server_socket.listen(1)
while True:
conn, addr = server_socket.accept()
p = Thread(target=talk, args=(conn,))
p.start()
conn.close()
if __name__ == '__main__':
server('127.0.0.1', 8081)