Python3:线程在加入后仍然活动
这是我的密码Python3:线程在加入后仍然活动,python,multithreading,Python,Multithreading,这是我的密码 def timeout(seconds_before_timeout): def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): res = [ Exception("function [%s] timeout [%s seconds] exceeded!"
def timeout(seconds_before_timeout):
def deco(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
res = [
Exception("function [%s] timeout [%s seconds] exceeded!"
% (func.__name__, seconds_before_timeout))
]
def new_func():
try:
res[0] = func(*args, **kwargs)
except Exception as ex:
res[0] = ex
thread = Thread(target=new_func)
thread.daemon = True
try:
thread.start()
thread.join(seconds_before_timeout)
except Exception as ex:
print("error starting thread")
raise ex
ret = res[0]
if isinstance(ret, BaseException):
raise ret
return ret
return wrapper
return deco
和超时功能,我用于:
@timeout(2)
def listen_for_a_new_campaign(self):
"""
Start listening for new campaign in list_campaign queue
"""
while True:
try:
for method_frame, properties, body \
in self.obj_requester_channel.consume(LIST_CAMPAIGN_QUEUE):
body_dict = literal_eval(body.decode("utf-8"))
message_number = body_dict["Msg_Count"]
n_message = min(message_number, BATCH_SIZE)
identify(n_message)
a_request = {
"campaign_request": body_dict,
"campaign_ack" : method_frame.delivery_tag,
"n_message" : n_message
}
identify(a_request)
return a_request
# Acknowledge the message
n_requeued_messages = self.obj_requester_channel.cancel()
print("Requeued %i messages" % n_requeued_messages)
break
except pika.exceptions.ConnectionWrongStateError:
print("Create connection ...")
self.create_connection()
continue
except pika.exceptions.ChannelWrongStateError:
print("Create connection ...")
self.create_connection()
self.obj_requester_channel = self.obj_connection.channel()
self.obj_requester_channel.queue_declare(queue=LIST_CAMPAIGN_QUEUE)
self.obj_campaign_channel = self.obj_connection.channel()
continue
当我运行我的程序时,我通过htop检查了所有进程,下面是结果,所有线程都处于活动状态:
我不知道这有什么不对。
我在我的笔记本电脑上运行这段代码,一切正常,但当我将它们部署到EC2实例时,我发现了那个些问题。
救救我
join()
如果线程未在超时内终止,则不会终止线程。如果线程在超时时间内没有返回,您是否打算杀死它?是的,因为我使用了一些AWS服务,所以我想更新凭据AW,我不知道为什么我的程序在本地pc上运行正常,然后在EC2上运行,但没有工作。我将一起删除超时
装饰程序,您不需要为此生成线程。我还将从此方法中删除while循环,并在调用方法中处理这些错误。我希望每个2s侦听一个队列Rabbitmq。如果删除while循环,则无法侦听新请求