如何同时运行两个python循环? [英] How do I run two python loops concurrently?

查看:2131
本文介绍了如何同时运行两个python循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Python中有以下内容

Suppose I have the following in Python

# A loop
for i in range(10000):
    Do Task A

# B loop
for i in range(10000):
    Do Task B

如何在Python中同时运行这些循环?

How do I run these loops simultaneously in Python?

推荐答案

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

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.

这篇关于如何同时运行两个python循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆