How do I implement my own advanced Producer/Consumer scenario?

前端 未结 5 1876
无人共我
无人共我 2021-01-24 00:56

NOTE:
i did a complete rework of my question. you can see the original question via the change-history.


i\'m in the need of a "mighty&qu

5条回答
  •  忘了有多久
    2021-01-24 01:40

    What you want could be done with conditionvariables. I'll compose a pseudo-code example, shouldn't be too hard to implement.

    One thread has something along the lines of:

    while(run)
      compose message
      conditionvariable.lock()
      add message to queue
      conditionvariable.notifyOne()
      conditionvariable.release()
    

    While the other thread has something along these lines

    while(threadsafe_do_run())
      while threadsafe_queue_empty()
           conditionvariable.wait()
      msg = queue.pop()
      if msg == "die"
          set_run(false)
      conditionvariable.release()
      send msg
    

    So if you don't get any messages push a die-message. Same thing when all messages have been processed.

    do_run() and queue_empty() should check their things thread-safely, use appropriate locks.

    wait() returns when notifyOne() is called and then the queue has a msg to send. in most frameworks the conditionvariable already has the lock, you might need to add the lock-statement yourself in .NET.

提交回复
热议问题