Are Generators Threadsafe?

后端 未结 6 856
闹比i
闹比i 2020-12-02 09:29

I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next

6条回答
  •  醉梦人生
    2020-12-02 09:56

    It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.

    The common approach is to use the master-slave pattern (now called farmer-worker pattern in PC). Make a third thread which generates data, and add a Queue between the master and the slaves, where slaves will read from the queue, and the master will write to it. The standard queue module provides the necessary thread safety and arranges to block the master until the slaves are ready to read more data.

提交回复
热议问题