用 Python 实现的线程池
来源:互联网 发布:mac桌面隐藏硬盘 编辑:程序博客网 时间:2024/06/01 11:00
import
Queue, threading, sys
from
threading
import
Thread
import
time,urllib
# working thread
class
Worker(Thread):
worker_count
=
0
def
__init__(
self
, workQueue, resultQueue, timeout
=
0
,
*
*
kwds):
Thread.__init__(
self
,
*
*
kwds )
self
.
id
=
Worker.worker_count
Worker.worker_count
+
=
1
self
.setDaemon(
True
)
self
.workQueue
=
workQueue
self
.resultQueue
=
resultQueue
self
.timeout
=
timeout
def
run(
self
):
''' the get-some-work, do-some-work main loop of worker threads '''
while
True
:
try
:
callable
, args, kwds
=
self
.workQueue.get(timeout
=
self
.timeout)
res
=
callable
(
*
args,
*
*
kwds)
print
"worker[%2d]: %s"
%
(
self
.
id
,
str
(res) )
self
.resultQueue.put( res )
except
Queue.Empty:
break
except
:
print
'worker[%2d]'
%
self
.
id
, sys.exc_info()[:
2
]
class
WorkerManager:
def
__init__(
self
, num_of_workers
=
10
, timeout
=
1
):
self
.workQueue
=
Queue.Queue()
self
.resultQueue
=
Queue.Queue()
self
.workers
=
[]
self
.timeout
=
timeout
self
._recruitThreads( num_of_workers )
def
_recruitThreads(
self
, num_of_workers ):
for
i
in
range
( num_of_workers ):
worker
=
Worker(
self
.workQueue,
self
.resultQueue,
self
.timeout )
self
.workers.append(worker)
def
start(
self
):
for
w
in
self
.workers:
w.start()
def
wait_for_complete(
self
):
# ...then, wait for each of them to terminate:
while
len
(
self
.workers):
worker
=
self
.workers.pop()
worker.join( )
if
worker.isAlive()
and
not
self
.workQueue.empty():
self
.workers.append( worker )
print
"All jobs are are completed."
def
add_job(
self
,
callable
,
*
args,
*
*
kwds ):
self
.workQueue.put( (
callable
, args, kwds) )
def
get_result(
self
,
*
args,
*
*
kwds ):
return
self
.resultQueue.get(
*
args,
*
*
kwds )
[Python]代码片段
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def
test_job(
id
, sleep
=
0.001
):
try
:
urllib.urlopen(
'https://www.gmail.com/'
).read()
except
:
print
'[%4d]'
%
id
, sys.exc_info()[:
2
]
return
id
def
test():
import
socket
socket.setdefaulttimeout(
10
)
print
'start testing'
wm
=
WorkerManager(
10
)
for
i
in
range
(
500
):
wm.add_job( test_job, i, i
*
0.001
)
wm.start()
wm.wait_for_complete()
- 用 Python 实现的线程池
- 用 Python 实现的线程池
- Python 线程池的实现
- Python的线程池实现
- python线程池的实现
- python:线程池的实现
- python实现的线程池
- Python实现线程池
- python实现线程池
- python线程池实现
- Python实现线程池
- Python线程池实现
- Python实现线程池
- 线程池python实现
- python 线程池实现
- python实现线程池
- python实现线程池
- python实现线程池
- hdu zipper 1501
- C语言中printf格式化输出函数
- 《Getting Started with D3》中文翻译(第二章)
- Latex使用-控制表格或者图形的显示位置
- Android学习笔记11:下载文件案例遇到了问题
- 用 Python 实现的线程池
- 封装过的文件读、写、删除、下载
- 手把手学习企业型网站之三firework做顶部的banner+nav
- java 工厂模式
- 封装过的文件上传方法
- 几个常用Unicode编码
- 进程和线程同步的方法
- Struts2实现文件上传
- 虚拟机调优