python 学习_第四模块 并发编程(多线程)
Posted augustyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 学习_第四模块 并发编程(多线程)相关的知识,希望对你有一定的参考价值。
python 学习_第四模块 并发编程(多线程)
1 开启线程方式
from threading import Thread import time def say(name): time.sleep(2) print("%s hello"%name) if __name__ =="__main__": t = Thread(target=say,args=("alex",)) t.start() print("主线程")
from threading import Thread import time class say(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 = say("alex") t.start() print("主线程")
基于套接字实现多线程
from socket import * from threading import Thread def communicate(conn): while True: try: data = conn.recv(1024) if not data:break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port): server = socket(AF_INET,SOCK_STREAM) server.bind((ip,port)) server.listen(5) while True: conn,addr = server.accept() t = Thread(target=communicate,args=(conn,)) t.start() server.close() if __name__ == "__main__": server("127.0.0.1",8080)
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")) data = client.recv(1024) print(data.decode("utf-8")) client.close()
以上是关于python 学习_第四模块 并发编程(多线程)的主要内容,如果未能解决你的问题,请参考以下文章