JJ_Jason
JJ_Jason

Reputation: 369

A non priority queue with insert priority

Google is giving me headaches with this search term.

I need a thread safe mechanism to achieve the following. A thread safe list with insert priority over read.

I need to always be able to insert a message (let's say) to the queue (or whatever) and occasionally, be able to read. So reading, cannot, ever, interfere with inserting.

Thanks.

EDIT: Reading would also mean clearing the red part.

EDIT2: Maybe helpful, there is a single reader and a single writer.

EDIT3: Case scenario: 10 inserts per second for a period of 1 minute (or max possible using the hardware on which the software is on). Then a insert pause of 1 minute. Then 20 inserts (or max possible using the hardware on which the software is on) in 2 seconds for a period of 30 sec. Then a pause of 30 sec. Then the pause is used for max number of reads. I don't know if I am being clear enough. Obviously not. (PS: I don't know when the pause will occur, that is the problem). Max acc. delay for insert: the time for the Enqueue or Add method to finish.

ADDITIONAL: Could a ConcurrentDictionary with a AddOrUpdate with TryGetValue and TryRemove be used?

Upvotes: 0

Views: 341

Answers (1)

cellik
cellik

Reputation: 2136

Construct your queue as a linked list of objects. Keep a reference to the head and the tail of the queue. See below the pseudo code which roughly tells the idea

QueueEntity Head;
QueueEntity Tail

class QueueEntity
{
       QueueEntity Prev;
       QueueEntity Next;
       ...   //queue content; 
}

and then do this:

//Read
lock(Tail)
{
  //get the content
  Tail=Tail.Prev;
}

//Write
lock(Head)
{
   newEntity = new QueueEntity();
   newEntity.Next = Head ;
   Head.Prev = newEntity;
   Head = newEntity;
}

Here you have separate locks for reading and writing and they won't block each other unless there is only one entiry in your queue.

Upvotes: 1

Related Questions