- 论坛徽章:
- 0
|
下面是我的代码res是个全局变量
if __name__ == '__main__':
import random
import time
# the work the threads will have to do (rather trivial in our example)
def do_something(data):
time.sleep(random.randint(1,5))
result = round(random.random() * data, 5)
print(result)
# just to show off, we throw an exception once in a while
#if result > 3:
#raise RuntimeError("Something extraordinary happened!")
return result
# this will be called each time a result is available
def print_result(request, result):
res+=result
print "**Result: %s from request #%s" % (result, request.requestID)
# this will be called when an exception occurs within a thread
def handle_exception(request, exc_info):
print "Exception occured in request #%s: %s" % \
(request.requestID, exc_info[1])
# assemble the arguments for each job to a list...
data = [random.randint(1,10) for i in range(2)]
# ... and build a WorkRequest object for each item in data
requests = makeRequests(do_something, data, print_result, handle_exception,)
# or the other form of args_lists accepted by makeRequests: ((,), {})
"""
data = [((random.randint(1,10),), {}) for i in range(20)]
requests.extend(
makeRequests(do_something, data, print_result, handle_exception)
)
"""
# we create a pool of 3 worker threads
main = ThreadPool(3)
global res
res=''
# then we put the work requests in the queue...
for req in requests:
main.putRequest(req)
#print "Work request #%s added." % req.requestID
sfd=str(req.callable)
if sfd.find('do_something') > 0:
print "nihao"
# or shorter:
# [main.putRequest(req) for req in requests]
# ...and wait for the results to arrive in the result queue
# by using ThreadPool.wait(). This would block until results for
# all work requests have arrived:
# main.wait()
# instead we can poll for results while doing something else:
main.wait()
print(res)
"""
i = 0
while 1:
try:
main.poll()
print "Main thread working..."
time.sleep(0.5)
if i == 10:
print "Adding 3 more worker threads..."
main.createWorkers(3)
i += 1
except KeyboardInterrupt:
print "Interrupted!"
break
except NoResultsPending:
print "All results collected."
break
"""
我执行后的出错结果
nihao
nihao
8.41607
Traceback (most recent call last):
File "C:\Documents and Settings\我\桌面\新建文件夹\temp\threadpool.py", line 3
23, in ?
main.wait()
File "C:\Documents and Settings\我\桌面\新建文件夹\temp\threadpool.py", line 2
28, in wait
self.poll(True)
File "C:\Documents and Settings\我\桌面\新建文件夹\temp\threadpool.py", line 2
18, in poll
request.callback(request, result)
File "C:\Documents and Settings\我\桌面\新建文件夹\temp\threadpool.py", line 2
82, in print_result
res+=result
UnboundLocalError: local variable 'res' referenced before assignment |
|