Home > Blockchain >  Synchronization when accessing two ends of a queue from different threads
Synchronization when accessing two ends of a queue from different threads

Time:03-29

I have one thread t1 which writes some data into a queue in the following manner:

while True:

  // generate data
  lock (myQueue)
  {            
    myQueue.Enqueue(data);
  }

I have my main thread which occasionally invokes the following function that uses queue data:

lock (myQueue)
{
  if (myQueue.Count == 0) return false;
}

Pose[] frame = myQueue.Dequeue()

Notice how the dequeue call is NOT locked. My thougt process here is, that if I ensure in a locked manner that the length is at least 1, my function will always read that one element and the other thread will only write behind this element if its writing at the same time. Is this correct or will I run into threading issues since they are still accessing the same object simultaneously?

CodePudding user response:

No, you are not allowed to access a non-thread-safe object from multiple threads without synchronization. If you do it, the behavior of your program becomes undefined. Here is how you could fix your code:

Pose[] frame;
lock (myQueue)
{
    if (myQueue.Count == 0) return false;
    frame = myQueue.Dequeue();
}
// Here use the frame

...or more succinctly:

Pose[] frame;
lock (myQueue)
{
    if (!myQueue.TryDequeue(out frame)) return false;
}
// Here use the frame
  • Related