(19)ThreadPoolExecutor線程池

# 線程池app

# 實例化線程池 ThreadPoolExcutor (推薦cpu_count*(n+1))異步

# 異步提交任務 submit / mapide

# 阻塞直到任務完成 shutdown函數

# 獲取子線程的返回值 resultspa

# 使用回調函數 add_done_callback線程

(1)基本用法:code

from concurrent.futures import ThreadPoolExecutor

def func(i):

    print("thread is start",i)

    print("thread is end ")

if __name__ == "__main__":

    p = ThreadPoolExecutor(5)

    p.submit(func,1)  #啓動線程

    p.shutdown()  # 至關於join+close

print("主線程")
View Code

執行結果:對象

thread is start 1
thread is end 
主線程
View Code

(2)返回值 ( 經過對象.result()拿到結果 )blog

from concurrent.futures import ThreadPoolExecutor
def func(i):
    print("thread %s start" % (i))
    print("thread %s end" % (i))
    return i * "*"
tp = ThreadPoolExecutor(5)
lst = []
for i in range(20):
    res = tp.submit(func,i) #返回值也是對象
    lst.append(res)
tp.shutdown()
for res in lst:
    print(res.result())
View Code

執行結果:回調函數

thread 0 start
thread 0 end
thread 1 start
thread 2 start
thread 1 endthread 2 end

thread 3 start
thread 3 end
thread 4 start
thread 4 end
thread 5 startthread 6 startthread 7 start
thread 7 end
thread 8 start
thread 8 end

thread 9 start

thread 6 end
thread 10 start
thread 10 end
thread 11 start
thread 11 end
thread 12 start
thread 12 end
thread 13 start
thread 13 end
thread 14 start
thread 14 end
thread 15 startthread 9 endthread 5 end
thread 16 start
thread 16 end
thread 17 start
thread 15 end
thread 18 start
thread 18 end
thread 19 start
thread 17 end

thread 19 end


*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
**************
***************
****************
*****************
******************
*******************
主線程
View Code

(3)map 返回生成器

from concurrent.futures import ThreadPoolExecutor
from threading import current_thread as ct
def func(i):
    print("thread",i,ct().ident)
    print("thread %s end" % (i))
    return i * "*"
tp = ThreadPoolExecutor(5)
res = tp.map(func,range(20))
tp.shutdown()
for i in res: # 生成器
    print(i)
View Code

執行結果:

thread 0 9336
thread 0 end
thread 1 9336
thread 1 end
thread 2 9336
thread 2 end
thread 3 3348
thread 3 end
thread 4 10116
thread 4 end
thread 5 3348
thread 5 endthread
thread thread7   8 9292
thread 8 end
6 thread 9 9336
thread 6 end
thread9292
thread 9 end
thread 11 10 9336 9292

threadthread 10 end
thread 13 thread3348
 thread 11 end
thread 15 thread 7 end
thread 16 12 9292
thread 15 end
14 3348
thread 16 end
10116
thread 14 endthread 17 3348
thread 17 end
thread  thread 19 3348
thread 19 end

10068933618

thread 13 end
thread 12 end 9292

thread 18 end

*
**
***
****
*****
******
*******
********
*********
**********
***********
************
*************
**************
***************
****************
*****************
******************
*******************
View Code
相關文章
相關標籤/搜索