简体   繁体   English

一次运行 10 个循环

[英]Run 10 Loops at a time

Okay, so I can do this in PowerShell as that is my specialty, however, I having issues trying to accomplish this in Python.好的,所以我可以在 PowerShell 中执行此操作,因为这是我的专长,但是,我在尝试使用 Python 完成此操作时遇到了问题。

See my PowerShell example here on what I am trying to do.在此处查看我的PowerShell 示例,了解我正在尝试执行的操作。

Essentially this is what I am trying to do in pseudo-code:本质上,这就是我试图用伪代码做的事情:

objArray = [
    {"name": "Test User", "address": "123 Movie Road"}, 
    {"name": "Test User", "address": "444 Music Road"}
]

#I want to run the below loop 10 at a time

for obj in objArray: 
     print(obj["name"])

Obviously, this is oversimplified however, I hope this outlines what I need to do.显然,这过于简单化了,但我希望这概述了我需要做的事情。

You can use range with a step value.您可以将range与步长值一起使用。

step = 10
for batch_idx in range(0, len(objArray), step):
    for obj in objArray[batch_idx:(batch_idx + step)]:
        print(obj['name'])

You can extend this using, for example, multithreading:例如,您可以使用多线程来扩展它:

from threading import Thread

def foo(objects):
    for obj in objects:
        print(obj['name'])

step = 10
for batch_idx in range(0, len(objArray), step):
    objects = objArray[batch_idx:(batch_idx + step)]
    t = Thread(target=foo, args=(objects,))
    t.start()

To execute something in parallel/concurrent you need threads.要并行/并发执行某些操作,您需要线程。 Luckily Python has an easy to use API for this.幸运的是,Python 有一个易于使用的 API。 You need to import the threading library.您需要导入线程库。

To run an thread you need to create a new Thread object and start it.要运行一个线程,您需要创建一个新的 Thread 对象并启动它。 The Thread object needs at least a target argument, which tells him which function to run. Thread 对象至少需要一个target参数,它告诉他要运行哪个函数。

eg例如

import threading

def do_something():
    for i in range(10):
        print("Executed in thread")

thread = threading.Thread(target=do_something)

thread.start()

Note that the target must be an executable function.请注意,目标必须是一个可执行函数。 This means only enter pass the name without parenthesis.这意味着只输入不带括号的名称。

To run 10 threads you need to create 10 threads and start them.要运行 10 个线程,您需要创建 10 个线程并启动它们。 Your final code could something like this:你的最终代码可能是这样的:

import threading

objArray = [
    {"name": "Test User", "address": "123 Movie Road"}, 
    {"name": "Test User", "address": "444 Music Road"}
]


def my_loop():
    for obj in objArray: 
        print(obj["name"])

for i in range(10): 
    thread = threading.Thread(target=my_loop)
    thread.start()

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

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