【问题标题】:How to run 2 while loops in parallel processes in Python如何在 Python 的并行进程中运行 2 个 while 循环
【发布时间】:2019-04-28 11:29:42
【问题描述】:

我正在尝试在 python 中进行简单的聊天,我需要并行运行 2 个 while 循环。其中之一是每 1 秒从 blobstorage 读取消息。第二个是使用 input() 等待来自用户的新消息,将其存储在 blob 中,然后等待下一个输入。

我尝试过使用异步、线程、多处理,但我还没有解决这个问题。它似乎总是卡在正在运行的任何一个while循环上,并且它永远不会到达第二个线程/进程/函数。我在这里或网上找到的例子都没有帮助。

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()

最终结果将是运行 2 个并行进程,它们会检测其他人是否已向我发送消息以及我是否已向他们发送消息。

【问题讨论】:

  • 你的意思是嵌套的while循环,因为内循环取决于外循环值吗?

标签: python multithreading parallel-processing


【解决方案1】:

你不小心运行了你的函数,而不是把它作为参数传递:

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

应该是

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

注意() 在第二行被删除了。

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-01
    • 1970-01-01
    • 2018-09-06
    相关资源
    最近更新 更多