python中的執行緒池map的應用

2021-09-10 02:57:17 字數 1847 閱讀 3375

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)

ips = ['12.13.14.%s' % (ip + 1) for ip in range(30)]

pool.map(get_area, ips)

@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)

ips = ['12.13.14.%s' % (ip + 1) for ip in range(30)]

pool.map(get_area, ips)

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...

執行緒池submit和map的應用

執行緒池submit的應用 import time def timeit f start time time.time res f args,kwargs end time time.time return res python3.2版本之後才有的 import threading from con...

python中的執行緒池submit應用

描述 thread,threading,multiprocessing 池子,只放制定個執行緒 10個執行緒 執行緒池裡面的執行緒越多越好?import time def timeit f start time time.time res f args,kwargs end time time.ti...