How to use multiprocessing with class instances in Python?

后端 未结 3 1256
Happy的楠姐
Happy的楠姐 2021-01-30 23:06

I am trying to create a class than can run a separate process to go do some work that takes a long time, launch a bunch of these from a main module and then wait for them all to

3条回答
  •  梦毁少年i
    2021-01-30 23:07

    Instead of attempting to send a method itself (which is impractical), try sending a name of a method to execute.

    Provided that each worker runs the same code, it's a matter of a simple getattr(self, task_name).

    I'd pass tuples (task_name, task_args), where task_args were a dict to be directly fed to the task method:

    next_task_name, next_task_args = self.task_q.get()
    if next_task_name:
      task = getattr(self, next_task_name)
      answer = task(**next_task_args)
      ...
    else:
      # poison pill, shut down
      break
    

提交回复
热议问题