简体   繁体   English

Python:并行化嵌套的 for 循环

[英]Python: Parallelizing a nested for loop

I'm a little lost in trying to use the multiprocessing module.我在尝试使用multiprocessing模块时有点迷失了。 I have a simple nested loop to do some copying of attributes from one object to another:我有一个简单的嵌套循环,可以将属性从一个 object 复制到另一个:

        if objects:
            rb_from = obj_act.rigid_body
            # copy settings
            for o in objects:
                rb_to = o.rigid_body
                if o == obj_act:
                    continue
                for attr in self._attrs:
                    setattr(rb_to, attr, getattr(rb_from, attr))

If nothing else, I'd like to parallelize the inner loop, but it's not clear to me how to do that.如果不出意外,我想并行化内部循环,但我不清楚如何做到这一点。 Most of the examples here focus on using the map function of multiprocessing , but I don't really care about the return value from setattr , I just want those calls to execute in parallel.这里的大多数示例都集中在使用map function 的multiprocessing ,但我并不真正关心setattr的返回值,我只是希望这些调用并行执行。

You may not achieve what you want using multiprocessing .您可能无法使用multiprocessing实现您想要的。 (Or, it could be rather complex.) Variables out of the context are not shared among processes. (或者,它可能相当复杂。)上下文之外的变量不会在进程之间共享。 But they are among threads.但它们在线程之间。

You can simply use threading and parallelize copying executions.您可以简单地使用threading并并行化复制执行。

    def copy_attributes(self, obj_act, o): 
        rb_from = obj_act.rigid_body

        rb_to = o.rigid_body
        if o == obj_act:
            return
        for attr in self._attrs:
            setattr(rb_to, attr, getattr(rb_from, attr))

    ...

            for o in objects:
                threading.Thread(
                    target=self.copy_attributes, args=(obj_act, o)
                ).start()

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

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