**描述:
_thread, threading, multiprocessing
池子, 只放制定個執行緒(10個執行緒),
執行緒池裡面的執行緒越多越好?
import time
def timeit(f):
start_time = time.time()
res = f(*args, **kwargs)
end_time = time.time()
return res
# python3.2版本之後才有的;
import threading
from concurrent.futures import threadpoolexecutor, wait
from urllib.request import urlopen
def get_area(ip):
url = "" % (ip)
urlobj = urlopen(url)
# 服務端返回的頁面資訊, 此處為字串型別
pagecontent = urlobj.read().decode('utf-8')
# 2. 處理json資料
import json
# 解碼: 將json資料格式解碼為python可以識別的物件;
dict_data = json.loads(pagecontent)
print("""
%s所在城市: %s
所在國家: %s
""" % (ip, dict_data['city'], dict_data['country']))
@timeit
def use_ten_thread():
# 1. 例項化線城池物件,線城池裡面包含5個執行緒執行任務;
pool = threadpoolexecutor(max_workers=10)
futures =
for i in range(30):
print("當前執行緒數:", threading.activecount())
ip = '12.13.14.%s' %(i+1)
# 往執行緒池裡面扔需要執行的任務, 返回的是乙個物件(_base.future()),
f1 = pool.submit(get_area, ip)
# 等待futures裡面所有的子執行緒執行結束, 再執行主線程(join())
wait(futures)
@timeit
def use_hundred_thread():
# 1. 例項化線城池物件,線城池裡面包含5個執行緒執行任務;
pool = threadpoolexecutor(max_workers=100)
futures =
for i in range(30):
print("當前執行緒數:", threading.activecount())
ip = '12.13.14.%s' %(i+1)
# 往執行緒池裡面扔需要執行的任務, 返回的是乙個物件(_base.future()),
f1 = pool.submit(get_area, ip)
wait(futures)
if __name__ == '__main__':
use_ten_thread()
use_hundred_thread()
python 執行緒池 Python的執行緒池
usr bin env python coding utf 8 concurrent 用於執行緒池和程序池程式設計而且更加容易,在python3.2中才有。import sys from concurrent.futures import threadpoolexecutor,as complete...
python 執行緒池 python執行緒池原始碼解析
本篇主要講下threadpoolexecutor的實現。由於業務量不大,且一直使用框架進行程式設計,對執行緒的理解一直很模糊,基本處於不想阻塞程式執行,起乙個執行緒啟動任務的階段。總感覺自己好像會執行緒一樣,實則一直處於一種懵懂狀態,通過一段時間檢視一些別人寫的原始碼,終於有所悟,也記錄下自己的學習...
python執行緒池
import time threadpool為執行緒池模組 import threadpool deftest str print str time.sleep 2 if name main starttime time.time 建立執行緒池,最多建立的執行緒數為10 pool threadpoo...