Python multiprocessing: synchronizing file-like object

前端 未结 2 603
日久生厌
日久生厌 2021-02-09 08:12

I\'m trying to make a file like object which is meant to be assigned to sys.stdout/sys.stderr during testing to provide deterministic output. It\'s not meant to be fast, just re

相关标签:
2条回答
  • 2021-02-09 08:50

    I have encountered far fewer multiprocessing bugs with Python 2.7 than with Python 2.6. Having said this, the solution I used to avoid the "Exception in thread QueueFeederThread" problem is to sleep momentarily, possibly for 0.01s, in each process in which the the Queue is used. It is true that using sleep is not desirable or even reliable, but the specified duration was observed to work sufficiently well in practice for me. You can also try 0.1s.

    0 讨论(0)
  • 2021-02-09 08:59

    The solution came in two parts. I've successfully run the test program 200 thousand times without any change in output.

    The easy part was to use multiprocessing.current_process()._identity to sort the messages. This is not a part of the published API, but it is a unique, deterministic identifier of each process. This fixed the problem with PIDs wrapping around and giving a bad ordering of output.

    The other part of the solution was to use multiprocessing.Manager().Queue() rather than the multiprocessing.Queue. This fixes problem #2 above because the manager lives in a separate Process, and so avoids some of the bad special cases when using a Queue from the owning process. #3 is fixed because the Queue is fully exhausted and the feeder thread dies naturally before python starts shutting down and closes stdin.

    0 讨论(0)
提交回复
热议问题