同步和异步描述的是任务的提交方式,同步意味着等待,异步意味不等待。
阻塞和非阻塞描述的是程序的运行状态,阻塞意味着程序处于阻塞态,非阻塞意味着程序处于就绪态或运行态
测试代码1
文件名:async_nonblock.py
#!/bin/env python3
#coding = utf-8
import time
from threading import Thread
def start_async(*args):
func = args[0]
def start_thread(*args,**kwargs):
t = Thread(target=func,args=args,kwargs=kwargs)
t.start()
t.start()
return start_thread
@start_async
def new_thread(*args):
while True:
print('endless loop,blocking !!!!')
time.sleep(1)
if __name__ == '__main__':
new_thread()
t0 = time.time()
while time.time() - t0 < 12:
time.sleep(3)
print('main process is running !!!!')
测试代码2
#!/bin/env python3
#coding = utf-8
from multiprocessing import Process
import time
def task(name,n):
print('%s is running'%name)
time.sleep(n)
print('%s is over'%name)
if __name__ == '__main__':
start_time = time.time()
p_list = []
for i in range(1,4):
p = Process(target=task,args=('subprocess %s'%i,i))
p.start()
p_list.append(p)
for p in p_list:
p.join()
print('main process is running',time.time()-start_time)