python进程池和线程池_Python 的多线程/进程和线程池/进程池总结

废话不多说,直接上代码。使用了两个包,futures 和 multiprocessing,支持 ThreadPool 和 ProcessPool。

怎么区分进程和线程呢,简单的说就是多进程可以在任务列表里看见多个进程,多线程可以在任务列表里看到1个进程有多个线程。#coding:utf-8

from concurrent import futures

from multiprocessing.pool import ThreadPool

import urllib2

import multiprocessing

import os, sys

URLS = [

'http://www.aspone.me/',

'http://www.baidu.com/',

'http://www.openstack.org/',

'http://www.drcloud.cn/',

'http://www.163.com/',

'http://www.microsoft.com/',

'http://www.python.org/'

]

def load_url(url, timeout):

print 'accept mission {0}'.format(url)

return urllib2.urlopen(url, timeout=timeout).read()

if __name__ == "__main__":

if len(sys.argv) > 1:

if sys.argv[1] == '1':

pool = ThreadPool(3)

ret = dict((pool.apply_async(load_url, (url, 60)), url) for url in URLS)

pool.close()

pool.join()

for i in ret:

print '%r page is %d bytes' % (ret[i], len(i.get()))

if sys.argv[1] == '2':

with futures.ThreadPoolExecutor(max_workers = 3) as executor:

future_to_url = dict((executor.submit(load_url, url, 60), url) for url in URLS)

for future in futures.as_completed(future_to_url):

url = future_to_url[future]

if future.exception() is not None:

print '%r generated an exception: %s' % (url, future.exception())

else:

print '%r page is %d bytes' % (url, len(future.result()))

if sys.argv[1] == '3':

pool = multiprocessing.Pool(processes = 3)

ret = dict((pool.apply_async(load_url, (url, 60)), url) for url in URLS)

pool.close()

pool.join()

for i in ret:

print '%r page is %d bytes' % (ret[i], len(i.get()))

else:

print '\n' + '*' * 40 + '\n'

print 'execute: python ' + os.path.realpath(__file__) + ' (mod)\n'

print 'mod:'

print '    1:   multiprocessing.pool ThreadPool (ThreadPool)'

print '    2:   futures.ThreadPoolExecutor (ThreadPool)'

print '    3:   multiprocessing.Pool (ProcessPool)'

print '\n' + '*' * 40 + '\n'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值