我在用线程。线程以及t.start()和一个可调用列表,用于执行长时间运行的多线程处理。我的主线程被阻塞,直到所有线程都完成。但是,我希望t.start()在其中一个可调用函数抛出异常并终止其他线程时立即返回。在
使用t.join()检查执行的线程是否没有提供有关异常导致的失败的信息。在
代码如下:
import json
import requests
class ThreadServices:
def __init__(self):
self.obj = ""
def execute_services(self, arg1, arg2):
try:
result = call_some_process(arg1, arg2) #some method
#save results somewhere
except Exception, e:
# raise exception
print e
def invoke_services(self, stubs):
"""
Thread Spanning Function
"""
try:
p1 = "" #some value
p2 = "" #some value
# Call service 1
t1 = threading.Thread(target=self.execute_services, args=(a, b,)
# Start thread
t1.start()
# Block till thread completes execution
t1.join()
thread_pool = list()
for stub in stubs:
# Start parallel execution of threads
t = threading.Thread(target=self.execute_services,
args=(p1, p2))
t.start()
thread_pool.append(t)
for thread in thread_pool:
# Block till all the threads complete execution: Wait for all
the parallel tasks to complete
thread.join()
# Start another process thread
t2 = threading.Thread(target=self.execute_services,
args=(p1, p2)
t2.start()
# Block till this thread completes execution
t2.join()
requests.post(url, data= json.dumps({status_code=200}))
except Exception, e:
print e
requests.post(url, data= json.dumps({status_code=500}))
# Don't return anything as this function is invoked as a thread from
# main calling function
class Service(ThreadServices):
"""
Service Class
"""
def main_thread(self, request, context):
"""
Main Thread:Invokes Task Execution Sequence in ThreadedService
:param request:
:param context:
:return:
"""
try:
main_thread = threading.Thread(target=self.invoke_services,
args=(request,))
main_thread.start()
return True
except Exception, e:
return False
当我调用Service().main_thread(request,context)并且在执行t1时出现异常,我需要在main_线程中引发它并返回False。我如何为这个结构实现它。谢谢!!在
首先,你把事情搞得太复杂了。我会这样做:
这样你就可以任务。等等()改为引发错误。线程已经停止。所以您需要做的就是在完成后从池或整个池中删除它们的引用。你甚至可以:
^{pr2}$现在,不要严格使用这个(我的意思是Task()类),因为它需要添加很多东西才能真正使用。在
只是子类线程。线程()并通过重写run()和join()或添加像wait()这样的新函数来实现类似的概念。在
相关问题 更多 >
编程相关推荐