我正在为我的网站构建一个非阻塞聊天应用程序,我决定实现一些多处理来处理数据库查询和实时消息传递。
我假设当用户登陆给定 URL 以查看他们与其他人的对话时,我将启动脚本,开始多处理,消息将被添加到队列并显示在页面上,新消息将发送到与数据库交互的单独队列等。(随之而来的是常规消息功能。)
但是,当用户离开此页面时会发生什么?我假设我需要退出这些不同的进程,但目前,这并不适合“干净”的退出。我将不得不终止进程并根据多处理文档:
Warning: If this method (terminate()) is used when the associated process is using a pipe
or queue then the pipe or queue is liable to become corrupted and may become
unusable by other process.Similarly, if the process has acquired a lock or
semaphore etc. then terminating it is liable to cause other processes to
deadlock.
我也调查过sys.exit()
;terminate()
但是,如果不使用各种进程,它不会完全退出脚本。
这是我为解决此问题而简化的代码。如果我需要改变它,那完全没问题。我只是想确保我正在适当地处理这个问题。
import multiprocessing
import Queue
import time
import sys
## Get all past messages
def batch_messages():
# The messages list here will be attained via a db query
messages = [">> This is the message.", ">> Hello, how are you doing today?", ">> Really good!"]
for m in messages:
print m
## Add messages to the DB
def add_messages(q2):
while True:
# Retrieve from the queue
message_to_db = q2.get()
# For testing purposes only; perfrom another DB query to add the message to the DB
print message_to_db, "(Add to DB)"
## Recieve new, inputted messages.
def receive_new_message(q1, q2):
while True:
# Add the new message to the queue:
new_message = q1.get()
# Print the message to the (other user's) screen
print ">>", new_message
# Add the q1 message to q2 for databse manipulation
q2.put(new_message)
def shutdown():
print "Shutdown initiated"
p_rec.terminate()
p_batch.terminate()
p_add.terminate()
sys.exit()
if __name__ == "__main__":
# Set up the queue
q1 = multiprocessing.Queue()
q2 = multiprocessing.Queue()
# Set up the processes
p_batch = multiprocessing.Process(target=batch_messages)
p_add = multiprocessing.Process(target=add_messages, args=(q2,))
p_rec = multiprocessing.Process(target=receive_new_message, args=(q1, q2,))
# Start the processes
p_batch.start() # Perfrom batch get
p_rec.start()
p_add.start()
time.sleep(0.1) # Test: Sleep to allow proper formatting
while True:
# Enter a new message
input_message = raw_input("Type a message: ")
# TEST PURPOSES ONLY: shutdown
if input_message == "shutdown_now":
shutdown()
# Add the new message to the queue:
q1.put(input_message)
# Let the processes catch up before printing "Type a message: " again. (Shell purposes only)
time.sleep(0.1)
我应该如何处理这种情况?我的代码是否需要从根本上修改?如果需要,我应该怎么做才能修复它?
任何想法、评论、修订或资源表示赞赏。
谢谢!