(21)回调函数

回调函数

就是一个参数,将这个函数作为参数传到另一个函数里面.

函数先执行,再执行当参数传递的这个函数,这个参数函数是回调函数

(1)线程池----->是由子线程实现的

from concurrent.futures import ThreadPoolExecutor

from threading import current_thread as cthread

import time

def func(i):

print("thread",i,cthread().ident)

time.sleep(1)

print("thread %s end" % (i))

return i * "*"

def call_back(args): # 回调函数,args 是func函数的返回值(是一个对象)

print("call back : ",cthread().ident) # 子线程id号

print(args.result())

tp = ThreadPoolExecutor(5)

for i in range(20):

# 当执行完这个线程后 再直接执行call_back这个函数

tp.submit(func,i).add_done_callback(call_back)

tp.shutdown()

print("主线程",cthread().ident)

(2)进程池----->是由主进程实现的

from concurrent.futures import ProcessPoolExecutor

import os ,time

def func(i):

print("process",i,os.getpid())

time.sleep(1)

print("process %s end" % (i))

return i * "*"

def call_back(args): # args 是func函数的返回值(是一个对象)

print("call back : ",os.getpid()) # 主进程id号

print(args.result())

if __name__ == "__main__":

tp = ProcessPoolExecutor(5)

for i in range(20):

# 当执行完这个线程后 在直接执行call_back这个函数

tp.submit(func,i).add_done_callback(call_back)

tp.shutdown()

print("主线程",os.getpid())

 

猜你喜欢

转载自www.cnblogs.com/lyj910313/p/10787418.html
今日推荐