from multiprocessing import Process def C(): i = 0 while True: i += 1 yield i c = C() def F(j): print(j, c.__next__()) for j in range(5): Process(target = F, args = (j,)).start() 

How to make subprocesses use one C () generator? With the next generation of the value, not the initial one. For example, this code will produce 0 - 1, 1 - 1, 2 - 1 ... And the implementation only from this: 0 - 1, 1 - 2, 2 - 3 ... Or subprocesses copy the object generator and it does not get around this way ?

    1 answer 1

    As far as I understand, this will not work.

    This can be solved differently with Queue. Let's leave the generator in the main process, and the subprocesses will get the values.

    Here is the original answer to a similar question. The code is from there, somewhat modified.

    iolock serves only for the beauty of a demo output.

     import multiprocessing as mp NCORE = 4 def process(q, iolock): from time import sleep while True: stuff = q.get() if stuff is None: break with iolock: print("processing", stuff) # Обработка значения sleep(stuff) def C(): i = 0 while True: i += 1 yield i c = C() if __name__ == '__main__': q = mp.Queue(maxsize=NCORE) iolock = mp.Lock() pool = mp.Pool(NCORE, initializer=process, initargs=(q, iolock)) for item in c: # Здесь будет блокироваться, если в очереди уже NCORE элементов q.put(item) with iolock: print("queued", stuff) for _ in range(NCORE): # tell workers we're done q.put(None) pool.close() pool.join()