简体   繁体   中英

How to run 2 while loops in parallel processes in Python

I am trying to make a simple chat in python and i would need to run 2 while loops in parallel. One of which is reading messages from a blobstorage every 1sec. Second one would be to wait for a new message from the user with input(), store it on the blob and then wait for the next input.

I have tried using asyncio, threading, multiprocessing but i havent solved the issue. It always seems to be stuck on whichever while loop is being run and it never gets to the second thread/process/function. None of the examples i have found here or on the web have helped.

class MainChat():
    def listen_for_messages(self):
        while True:
            print("listener")
            # reading from db and detecting if any new messages have been sent to user
            #if new message is detected, print it out

    def message_writer(self):
        while True:
            print("writer")
            msg = input()
            # parse and send message to db

if __name__ == '__main__':
    chat = MainChat()
    Process(target=chat.listen_for_messages()).start()
    Process(target=chat.message_writer()).start()

End result would be to have 2 parallel processes running which detect if another person has sent a message to me and if i have sent a message to them.

You accidentally ran your function instead of passing it as a parameter:

Process(target=chat.listen_for_messages()).start()
Process(target=chat.message_writer()).start()

should be

Process(target=chat.listen_for_messages).start()
Process(target=chat.message_writer).start()

notice the () is removed on the second line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM