简体   繁体   English

如何在Python中的并行进程中运行2个while循环

[英]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. 我正在尝试在python中进行简单的聊天,我需要并行运行2 while循环。 One of which is reading messages from a blobstorage every 1sec. 其中之一是每1秒从内存存储区读取一次消息。 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. 第二个方法是等待带有input()的来自用户的新消息,将其存储在blob中,然后等待下一个输入。

I have tried using asyncio, threading, multiprocessing but i havent solved the issue. 我曾尝试使用asyncio,线程,多处理程序,但尚未解决问题。 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. 最终结果将是运行2个并行进程,这些进程将检测其他人是否向我发送了消息以及我是否向他们发送了消息。

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. 请注意()在第二行中已删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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