I am just learning how to do some multiprocessing with Python, and I would like to create a non-blocking chat application that can add/retrieve messages to/from a database. This is my somewhat primitive attempt (note: It is simplified for the purposes of this post); however, I would like to know how close/far off off the mark I am. Any comments, revisions, suggestions, etc. are greatly appreciated.
Thank you!
import multiprocessing
import Queue
import time
# Get all past messages
def batch_messages():
# The messages list here will be attained via a db query
messages = [">> This is a message.", ">> Hello, how are you doing today?", ">> Really good!"]
for m in messages:
print m
# Add messages to the DB
def add_messages(q):
# Retrieve from the queue
message_to_add = q.get()
# For testing purposes only; perfrom another DB query to add the message to the DB
print "(Add to DB)"
# Recieve new, inputted messages.
def receive_new_message(q, new_message):
# Add the new message to the queue:
q.put(new_message)
# Print the message to the screen
print ">>", new_message
if __name__ == "__main__":
# Set up the queue
q = multiprocessing.Queue()
# Print the past messages
batch_messages()
while True:
# Enter a new message
input_message = raw_input("Type a message: ")
# Set up the processes
p_add = multiprocessing.Process(target=add_messages, args=(q,))
p_rec = multiprocessing.Process(target=receive_new_message, args=(q, input_message,))
# Start the processes
p_rec.start()
p_add.start()
# Let the processes catch up before printing "Type a message: " again. (Shell purposes only)
time.sleep(1)
q
as a parameter. – Janne Karila Mar 21 at 14:48q
is now passed to the functions. Thanks. – JohnZ Mar 21 at 14:58