且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何同时运行两个python循环?

更新时间:2023-10-20 15:44:16

如果你想要并发,这里有一个非常简单的例子:

If you want concurrency, here's a very simple example:

from multiprocessing import Process

def loop_a():
    while 1:
        print("a")

def loop_b():
    while 1:
        print("b")

if __name__ == '__main__':
    Process(target=loop_a).start()
    Process(target=loop_b).start()

这只是我能想到的最基本的例子。请务必阅读 http://docs.python.org/library/multiprocessing.html了解发生了什么。

This is just the most basic example I could think of. Be sure to read http://docs.python.org/library/multiprocessing.html to understand what's happening.

如果您想要将数据发送回程序,我建议使用队列(在我的经验是最容易使用的)。

If you want to send data back to the program, I'd recommend using a Queue (which in my experience is easiest to use).

如果您不介意全局解释器锁。进程实例化更昂贵,但它们提供真正的并发。

You can use a thread instead if you don't mind the global interpreter lock. Processes are more expensive to instantiate but they offer true concurrency.