利用Python的装饰器一键开启多线程

  • 2020 年 7 月 28 日
  • 筆記

记录一下自己写的烂代码


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

从结果看,管道会产生一个阻塞效果,只有当它接收到消息后才会继续往下运行代码