网址怎么做成快捷方式,seo优化上首页,上海网站建设哪家,湖南搜索引擎推广多少钱一 threading模块介绍
multiprocess模块完全模仿了threading模块的接口#xff0c;二者在使用层面#xff0c;有很大的相似性
二 开启线程的两种方式
方式一 1 2 3 4 5 6 7 8 9 10 11 12 13 from threading import Thread import time def sayhi(name): time.sleep…一 threading模块介绍
multiprocess模块完全模仿了threading模块的接口二者在使用层面有很大的相似性
二 开启线程的两种方式
方式一 1 2 3 4 5 6 7 8 9 10 11 12 13 from threading import Thread import time def sayhi(name): time.sleep(2) print(%s say hello % name) if __name__ __main__: t Thread(targetsayhi, args(mike, )) t.start() print(主线程) 方式二 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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、基于多线程实现并发的套接字通信
客户端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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)) 服务端 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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(targettalk, args(conn,)) p.start() conn.close() if __name__ __main__: server(127.0.0.1, 8081)