利用@注解函数名(装饰器),可实现简单的异步非阻塞。上代码:
# -*- coding:utf-8 -*-
import time
from threading import Thread
class Async:
"""
使用装饰器实现多线程的异步非阻塞
"""
def start_async(*args):
fun = args[0]
def start_thread(*args, **kwargs):
"""
启动线程(内部方法)
"""
t = Thread(target=fun, args=args, kwargs=kwargs)
t.start()
return start_thread
@start_async
def new_thread(*args):
while 1:
print("这里是阻塞的死循环...")
time.sleep(1)
if __name__ == '__main__':
# 启动异步线程
Async().new_thread()
# 主线程
t0 = time.time()
while time.time() - t0 < 1000:
time.sleep(3)
print("主进程...")
运行结果: