學習日記0910線程池與進程池 同步調用與異步調用 函數回調
阿新 • • 發佈:2018-09-10
pid urn sleep call 解耦 __name__ .get ESS con
前提:線程池與進程池一般與同步調用與異步調用一起使用,而函數回調一般與異步調用一起使用
同步調用
提交完一個任務後,在原地等待,直到任務完完整整的運行完,得到返回的結果之後,再運行下一個函數,這樣會導致任務之間是串行運行
進程池+同步調用
from concurrent.futures import ProcessPoolExecutor import time,os,random def task(name): print(‘%s:%s‘ % (name, os.getpid())) time.sleep((random.randint(1, 3))) return123 if __name__ == ‘__main__‘: p = ProcessPoolExecutor(4) for i in range(10): res = p.submit(task,‘同步調用‘).result() print(res) p.shutdown(wait=True) print(‘主函數‘)
進程池+異步調用+函數回調
from concurrent.futures import ProcessPoolExecutor import time import random, os deftask(name): print(‘%s:%s‘ % (name, os.getpid())) time.sleep((random.randint(1, 3))) return 123 def re_task(future): time.sleep(1) print(‘函數task的運行結果是%s:%s‘ % (future.result(), os.getpid())) if __name__ == ‘__main__‘: p = ProcessPoolExecutor(4) for i in range(10): future= p.submit(task, ‘pid‘) future.add_done_callback(re_task) # 函數回調的代碼,實現的是將future對象傳遞給re_task函數,實現了函數之間的解耦合 p.shutdown(wait=True) print(‘zhu‘)
線程池+同步調用
from concurrent.futures import ThreadPoolExecutor from threading import current_thread import time,random def task(name): print(‘%s:%s‘ % (name, current_thread().name)) time.sleep((random.randint(1, 3))) return 123 if __name__ == ‘__main__‘: t = ThreadPoolExecutor(4) for i in range(10): res = t.submit(task,‘pid‘).result() print(res) t.shutdown(wait=True) print(‘zhu‘)
線程池+異步調用+函數回調
from concurrent.futures import ThreadPoolExecutor from threading import current_thread import time,random def task(name): print(‘%s:%s‘ % (name, current_thread().name)) time.sleep((random.randint(1, 3))) return 123 def re_task(future): time.sleep(1) print(‘函數task的運行結果是%s:%s‘ % (future.result(), current_thread().name)) if __name__ == ‘__main__‘: t = ThreadPoolExecutor(4) for i in range(10): future = t.submit(task,‘pid‘) future.add_done_callback(re_task) t.shutdown(wait=True) print(‘主線程!‘)
阻塞與非阻塞
阻塞:程序正在處理I\O操作程序會進入阻塞狀態
非阻塞:程序正在處在運行狀或者就緒態
程序的三種狀態:
學習日記0910線程池與進程池 同步調用與異步調用 函數回調