easythrees
easythrees

Reputation: 1660

Python: Parallelizing a nested for loop

I'm a little lost in trying to use the multiprocessing module. I have a simple nested loop to do some copying of attributes from one object to another:

        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.

Upvotes: 0

Views: 89

Answers (1)

ghchoi
ghchoi

Reputation: 5166

You may not achieve what you want using 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.

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

Upvotes: 1

Related Questions