import multiprocessing as mp from time import sleep class Cluster: def __init__(self, shards, function): self._workers = [mp.Process(target=self._run_single, args=(function, shard)) for shard in range(shards)] def run(self): for worker in self._workers: worker.start() return self def join(self): for worker in self._workers: worker.join() def _run_single(self, function, shard): function(shard) def function(shard): for i in range(3): print(shard, i) sleep(0.1) if __name__ == '__main__': mp.set_start_method('forkserver') Cluster(2, function).run().join()