记录一下自己写的烂代码 import time import threading def WithThread(obj): """这是一个开启线程的装饰器""" def Threads(*args): t = threading.Thread(target=obj, args=args) t.start() return Threads @WithThread def hello(name): while 1: print("hello",name) time.sleep(3) hello("c137-max") print("end") 运行结果 hello c137-max end hello c137-max hello c137-max hello c137-max .... 可以看到不会发生堵塞的情况, 但是停不了 如果想实现while死循环停下来的功能,可以使用管道功能 from multiprocessing import Pipe @WithThread def hello(name, conn): while 1: msg = conn.recv() if msg == "stop": break else: print(msg) print("hello", name) child_conn, parent_conn = Pipe() hello("c137-max", parent_conn) time.sleep(4) child_conn.send("你好阿") time.sleep(4) child_conn.send("stop") 运行结果 你好阿 hello c137-max 从结果看,管道会产生一个阻塞效果,只有当它接收到消息后才会继续往下运行代码
利用Python的装饰器一键开启多线程
内容版权声明:除非注明,否则皆为本站原创文章。