我最近一直在阅读和学习线程,以便可以在我的项目中使用它们。我阅读了许多文章,其中大多数人都说突然终止线程是一种不好的做法,但是没有一篇文章我是一名业余程序员,对此我讲得太多了,有人可以举一个例子给我做一个简短的解释,以便我理解这个事实。
@app.before_first_request
def activate_job():
global files_dict
global files_meta_dict
def run_user_job():
while True:
USER_QUEUE=User.query.filter_by(processing_status="queued").first()
if( bool(files_dict) and bool(files_meta_dict) and USER_QUEUE!=None): //check if dictionaries are empty
doc_details={}
print("admin queue is",USER_QUEUE)
doc_details["id"]=USER_QUEUE.doc_id
for key,value in files_dict.items():
if value==USER_QUEUE.doc_id: //dictionary reverse search
doc_details["name"]=key
break
try:
doc.main_write([doc_details], USER_QUEUE.email, USER_QUEUE.ref_no, json.loads(USER_QUEUE.user_data)) //parses a document and mails it
print("this sends mail")
USER_QUEUE.processing_status="processed"
db.session.merge(USER_QUEUE)
db.session.commit()
except Exception as e:
USER_QUEUE.processing_status="queued"
db.session.merge(USER_QUEUE)
db.session.commit()
print("Exception occured In the User queue thread",e)
def run_admin_job():
global files_dict
global files_meta_dict
while True:
ADMIN_QUEUE=User.query.filter(User.status!=0,User.final_mail_sent=="queued").first()
if( bool(files_dict) and bool(files_meta_dict) and ADMIN_QUEUE!=None): //check if dictionaries are empty
print("in if statement")
doc_details={}
print("doing admin job")
doc_details["id"]=ADMIN_QUEUE.doc_id
for key,value in files_dict.items():
if value==ADMIN_QUEUE.doc_id:
doc_details["name"]=key //dictionary reverse search
break
if(ADMIN_QUEUE.status!=0):
if(ADMIN_QUEUE.status==1):
try:
start_index,end_index=doc.get_index(ADMIN_QUEUE.parsed_doc_id, "{{Signature}}\n") //gets index of "{{Signature}}"
print("start index and end index",start_index,end_index)
doc.approve_sign(ADMIN_QUEUE.parsed_doc_id,start_index) //places a signature photo to the acquired index
doc.download_pdf(ADMIN_QUEUE.parsed_doc_id) //downloads pdf
doc.send_mail_flask_to_user(doc_details["name"],ADMIN_QUEUE.parsed_doc_id,ADMIN_QUEUE.email,True)
ADMIN_QUEUE.final_mail_sent="processed"
db.session.merge(ADMIN_QUEUE)
db.session.commit()
except Exception as e:
ADMIN_QUEUE.final_mail_sent="queued"
db.session.merge(ADMIN_QUEUE)
db.session.commit()
print("Exception occured at Admin queue thread while approving",e,doc_details,ADMIN_QUEUE.parsed_doc_id)
elif(ADMIN_QUEUE.status==-1):
doc.send_mail_flask_to_user(doc_details["name"],ADMIN_QUEUE.parsed_doc_id,ADMIN_QUEUE.email,False)
ADMIN_QUEUE.final_mail_sent="processed"
db.session.merge(ADMIN_QUEUE)
db.session.commit()
admin_thread_queue=threading.Thread(target=run_user_job)
user_thread_queue=threading.Thread(target=run_admin_job)
user_thread_queue.start()
admin_thread_queue.start()