- 论坛徽章:
- 0
|
if __name__ == '__main__':
import random
import time
res = []
global_locker=threading.Lock()
# 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):
global res
global_locker.acquire()
res.append(result)
print "**Result: %s from request #%s" % (result, request.requestID)
global_locker.release()
# 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(100)]
# ... 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(10)
#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)
print len(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
"""
修改的地方是红的,没太仔细看,有问题再告诉我吧
100条数据,10个线程执行,数据是随机出现的,我也就没仔细查,最后看结果的数目还是对的。 |
|