consumer/producer in c++

前端 未结 4 1688
灰色年华
灰色年华 2020-12-15 14:18

This is a classic c/p problem where some threads produce data while other read the data. Both the producer and consumers are sharing a const sized buffer. If the buffer is e

4条回答
  •  离开以前
    2020-12-15 14:44

    What I would do is this:

    • Make a data class that hides your queue
    • Create thread-safe accessor methods for saving a piece of data to the q, and removing a piece of data from the q ( I would use a single mutex, or a critical section for accessors)
    • Handle the case where a consumor doesn't have any data to work with (sleep)
    • Handle the case where the q is becoming too full, and the producers need to slow down
    • Let the threads go willy-nilly adding and removing as they produce / consume

    Also, remember to add a sleep into each and every thread, or else you'll peg the CPU and not give the thread scheduler a good spot to switch contexts and share the CPU with other threads / processes. You don't need to, but it's a good practice.

提交回复
热议问题