进程池

import multiprocessing
import time def do_calculation(data):
print(multiprocessing.current_process().name + " " + str(data))
time.sleep(3)
return data * 2 def start_process():
print ('Starting', multiprocessing.current_process().name) if __name__ == '__main__':
inputs = list(range(10))
print ('Input :' + str(inputs)) pool_size = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=pool_size,
initializer=start_process,
)

#more inputs
    #more_inputs = [11,12,13,14,15,16,17,18,19,20]
    #pool_outputs = pool.map(do_calculation, more_inputs) pool_outputs = pool.map(do_calculation, inputs)
pool.close() # no more tasks
pool.join() # wrap up current tasks print ('Pool :' + str(pool_outputs))

运行如下:

root # python pool.py
Input :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
('Starting', 'PoolWorker-1')
PoolWorker-1 0
('Starting', 'PoolWorker-2')
PoolWorker-2 2
PoolWorker-1 1
PoolWorker-2 3
PoolWorker-1 4
PoolWorker-2 6
PoolWorker-1 5
PoolWorker-2 7
PoolWorker-1 8
PoolWorker-1 9
Pool :[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

如果任务是动态添加可以用如下代码

import multiprocessing
import time def worker(data):
if data == 3:
time.sleep(10)
else:
time.sleep(1)
print(multiprocessing.current_process().name + " " + str(data))
return data * 2 def start_process():
print ('Starting', multiprocessing.current_process().name) #callback func
def say(res):
print res if __name__ == '__main__':
inputs = list(range(10))
print ('Input :' + str(inputs)) pool_size = multiprocessing.cpu_count()
pool = multiprocessing.Pool(processes=pool_size,
initializer=start_process,
) for i in inputs:
pool.apply_async(worker, (i,))
#pool.apply_async(worker, (i,), callback=say) pool.close() # no more tasks
pool.join() # wrap up current tasks

输出如下:

root # python pool2.py
Input :[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
('Starting', 'PoolWorker-1')
('Starting', 'PoolWorker-2')
PoolWorker-1 0
PoolWorker-2 1
PoolWorker-1 2
PoolWorker-1 4
PoolWorker-1 5
PoolWorker-1 6
PoolWorker-1 7
PoolWorker-1 8
PoolWorker-1 9
PoolWorker-2 3

线程池

import Queue
import sys
import threading
import time thread_count = 2
mutex = threading.Lock() class MyThread(threading.Thread):
def __init__(self, workQueue, resultQueue,timeout=0, **kwargs):
threading.Thread.__init__(self, kwargs=kwargs)
self.timeout = 1
self.setDaemon(True)
self.workQueue = workQueue
self.resultQueue = resultQueue
self.start() def run(self):
while True:
try:
callable, args, kwargs = self.workQueue.get(timeout=self.timeout)
res = callable(args, self.getName())
self.resultQueue.put(res) except Queue.Empty:
break
except :
print sys.exc_info()
raise class ThreadPool:
def __init__( self, num_of_threads=10):
self.workQueue = Queue.Queue()
self.resultQueue = Queue.Queue()
self.threads = []
self.__createThreadPool( num_of_threads ) def __createThreadPool( self, num_of_threads ):
for i in range( num_of_threads ):
thread = MyThread( self.workQueue, self.resultQueue )
self.threads.append(thread) def wait_for_complete(self):
while len(self.threads):
thread = self.threads.pop()
if thread.isAlive():
thread.join() def add_job( self, callable, args, **kwargs ):
while True:
if self.workQueue.qsize() < 10000:
self.workQueue.put( (callable,args,kwargs) )
break
time.sleep(0.1) def worker(data, threadid): if mutex.acquire(1):
print threadid, data
mutex.release() time.sleep(3)
return data * 2 if __name__ == '__main__': threadPool = ThreadPool(thread_count)
for i in range(10):
threadPool.add_job(worker, i) threadPool.wait_for_complete()
print 'result Queue\'s length == %d '% threadPool.resultQueue.qsize()
while threadPool.resultQueue.qsize():
print threadPool.resultQueue.get()
print 'end testing'

运行如下:

root # python g.py
Thread-1 0
Thread-2 1
Thread-1 2
Thread-2 3
Thread-1 4
Thread-2 5
Thread-1 6
Thread-2 7
Thread-1 8
Thread-2 9
result Queue's length == 10
0
2
4
6
8
10
12
14
16
18
end testing

简单测试了一下,如果worker函数需要做大量耗cpu的运算,用进程池速度比线程池快数倍。

2.492s VS 0.598s

python(进程池/线程池)的更多相关文章

  1. python并发编程-进程池线程池-协程-I/O模型-04

    目录 进程池线程池的使用***** 进程池/线程池的创建和提交回调 验证复用池子里的线程或进程 异步回调机制 通过闭包给回调函数添加额外参数(扩展) 协程*** 概念回顾(协程这里再理一下) 如何实现 ...

  2. Python学习之GIL&进程池/线程池

    8.6 GIL锁** Global interpreter Lock 全局解释器锁 实际就是一把解释器级的互斥锁 In CPython, the global interpreter lock, or ...

  3. Python并发编程05 /死锁现象、递归锁、信号量、GIL锁、计算密集型/IO密集型效率验证、进程池/线程池

    Python并发编程05 /死锁现象.递归锁.信号量.GIL锁.计算密集型/IO密集型效率验证.进程池/线程池 目录 Python并发编程05 /死锁现象.递归锁.信号量.GIL锁.计算密集型/IO密 ...

  4. Python标准模块--concurrent.futures 进程池线程池终极用法

    concurrent.futures 这个模块是异步调用的机制concurrent.futures 提交任务都是用submitfor + submit 多个任务的提交shutdown 是等效于Pool ...

  5. concurrent.futures模块(进程池/线程池)

    需要注意一下不能无限的开进程,不能无限的开线程最常用的就是开进程池,开线程池.其中回调函数非常重要回调函数其实可以作为一种编程思想,谁好了谁就去掉 只要你用并发,就会有锁的问题,但是你不能一直去自己加 ...

  6. Python-GIL 进程池 线程池

    5.GIL vs 互斥锁(*****) 1.什么是GIL(Global Interpreter Lock) GIL是全局解释器锁,是加到解释器身上的,保护的就是解释器级别的数据 (比如垃圾回收的数据) ...

  7. 13 并发编程-(线程)-异步调用与回调机制&进程池线程池小练习

    #提交任务的两种方式 #1.同步调用:提交完任务后,就在原地等待任务执行完毕,拿到结果,再执行下一行代码,导致程序是串行执行 一.提交任务的两种方式 1.同步调用:提交任务后,就在原地等待任务完毕,拿 ...

  8. python day 20: 线程池与协程,多进程TCP服务器

    目录 python day 20: 线程池与协程 2. 线程 3. 进程 4. 协程:gevent模块,又叫微线程 5. 扩展 6. 自定义线程池 7. 实现多进程TCP服务器 8. 实现多线程TCP ...

  9. Python之路——线程池

    1 线程基础 1.1 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2 线程同步——锁 多线程的优势在于可以同时运行多个任务(至少感觉起来是这样,其实Python中是伪多线程).但是当线程 ...

  10. 并发编程---线程queue---进程池线程池---异部调用(回调机制)

    线程 队列:先进先出 堆栈:后进先出 优先级:数字越小优先级越大,越先输出 import queue q = queue.Queue(3) # 先进先出-->队列 q.put('first') ...

随机推荐

  1. BZOJ 1969: [Ahoi2005]LANE 航线规划( 树链剖分 )

    首先我们要时光倒流, 倒着做, 变成加边操作维护关键边. 先随意搞出一颗树, 树上每条边都是关键边(因为是树, 去掉就不连通了)....然后加边(u, v)时, 路径(u, v)上的所有边都变成非关键 ...

  2. Labview学习之远程控制VI

    Labview学习之远程控制VI        从LabVIEW 6.1开始,LabVIEW集成了Remote Panels技术,允许用户直接在客户端计算机上打开并操作位于服务器端计算机上的VI的前面 ...

  3. .Net页面缓存OutPutCachexian详解

    一 它在Web.Config中的位置 <system.web> <!--页面缓存--> <caching> <outputCacheSettings> ...

  4. [转] jQuery 操作 JSON 数据

    jquery下json数组的操作用法实例: jquery中操作JSON数组的情况中遍历方法用的比较多,但用添加移除这些好像就不是太多了. 试过json[i].remove(),json.remove( ...

  5. Composer Yii2 不设置全局变量 归档安装 Win7

    1.下载Composer_installer.phar https://getcomposer.org/composer.phar 重命名为  composer_installer.phar 将文件放 ...

  6. Net Core- 配置组件

    Net Core- 配置组件 我们之前写的配置都是放置在配置文件Web.config或者app.config中,.net core提供了全新的配置方式,可以直接写在内存中或者写在文件中. .Net C ...

  7. linux服务器在运行210天左右宕机

    减小字体 增大字体 作者:错新网  来源:www.cuoxin.com  发布时间:2014-2-25 19:21:32 错新网讯   最近几天,一批linux线上的服务器接连宕机,当时以为是硬件问题 ...

  8. RTTI-CLASS

    package com.xt.test; interface Test1Interface { } interface Test2Interface { } class Test1 implement ...

  9. 串的模式匹配——Brute-Force算法

    Brute-Force算法的基本思路为:从目标串s=“s0s1...sn-1”的第一个字符开始和模式串t=“t0t1t2...tn-1”中的第一个字符比较,若相等,则继续逐个比较后续字符: 否则从目标 ...

  10. MyEclipse启动时报 Unable to acquire application service. Ensure that the org.eclips

    今天MyEclipse启动时报如下错误: !SESSION 2012-02-12 11:32:55.198 ---------------------------------------------- ...