示例
标准线程多进程,生产者/消费者示例:
Worker越多,问题越大
复制代码 代码如下:
# -*- coding: utf8 -*-
import os
import time
import Queue
import threading
from PIL import Image
def create_thumbnail(filename, size=(128, 128)):
try:
fp, fmt = filename.rsplit('.', 1)
im = Image.open(filename)
im.thumbnail(size, Image.ANTIALIAS)
im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
return '%s thumbnail success!' % filename
except Exception:
return '%s thumbnail failed!' % filename
def get_image_paths(folder):
return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]
class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue
def run(self):
while True:
content = self._queue.get()
if isinstance(content, str) and content == 'quit':
break
respone = create_thumbnail(content)
print 'Bye bye!'
def Producer():
filenames = get_image_paths('images')
queue = Queue.Queue()
worker_threads = build_worker_pool(queue, 4)
start_time = time.time()
for filename in filenames:
queue.put(filename)
for worker in worker_threads:
queue.put('quit')
for worker in worker_threads:
worker.join()
print time.time() - start_time
def build_worker_pool(queue, size):
workers = []
for _ in range(size):
worker = Consumer(queue)
worker.start()
workers.append(worker)
return workers
if __name__ == '__main__':
Producer()
map
Map能够处理集合按顺序遍历,最终将调用产生的结果保存在一个简单的集合当中。
复制代码 代码如下:
# -*- coding: utf8 -*-
import os
import time
from multiprocessing import Pool
from PIL import Image
def create_thumbnail(filename, size=(128, 128)):
try:
fp, fmt = filename.rsplit('.', 1)
im = Image.open(filename)
im.thumbnail(size, Image.ANTIALIAS)
im.save((fp + '_'+'x'.join(str(i) for i in size) + '.'+fmt), im.format)
return '%s thumbnail success!' % filename
except Exception:
return '%s thumbnail failed!' % filename
def get_image_paths(folder):
return [os.path.join(folder, f) for f in os.listdir(folder) if 'png' in f]
def main():
filenames = get_image_paths('images')
start_time = time.time()
pool = Pool(4)
pool.map(create_thumbnail, filenames)
pool.close()
pool.join()
print time.time() - start_time
if __name__ == '__main__':
main()
Python,并行任务
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]