开发者

Is there a way to QUEUE threads?

I am trying to do buffer full simulation. When my buffer gets full I need to copy it for further processing, copying is a mutually exclusive operation but further processing is not. My flow of actions is like this , I check the buffer full condition each time when I am about to write something if the condition is true I copy the current buffer & process it & then write the new message.

I have multiple writing threads & the messages should be written in sequence only. my functions in brief are as follow

bwrite(data)
{
  lock(m1);
  //invoke copy thread
  lock(m1);
  // Do write message
}

copy(data)
{
 //copy the data
 unlock(m1);
 //Do further processing
}

The problem is that once the copying is done, the messages are written in any sequence like for example if thread01 , & thread02 are there & if thread01 copies the first I dont have any control over the fact that thread02 might star开发者_运维技巧t copying before thread01 has written its last message , so there may be a potential loss of a message.

Its been a long question , basically I need a way to put incoming threads in a queue so that I can guarantee the next execution sequence.


Why don't you just have the threads write to a shared queue? Then you can have another thread take elements off of the queue one-at-a-time and write them - this guarantees that they are written in the same order as they are queued. Now you just need to synchronize access to the queue to make it thread safe.


Yes, use a Semaphore http://en.wikipedia.org/wiki/Semaphore_%28programming%29


Actually I believe the best solution to this is to use a BlockingQueue. I'm sure if you google it you can find someone has posted sample c++ code for it but here is a sample of it's usage in java http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜