What is wrong with I am trying to enqueue?

Hi,

Can anyone help me out with how I am trying to enqueue and check the queue in my thread? My problem here is that the main thread doesn’t seem to pick up what the enqueueThis function is enqueueing. E.g. if I try to Debug.Log(thisQueue.Count) inside the enqueueThis function, it seems to work fine. But this doesn’t seem to apply to the main thread. Though the thread itself runs fine. It simply won’t update the queue with what I am trying to enqueue with the function.

I would be grateful for some feedback on this.

main thread:

while(threadIsActive)
{
   if(thisQueue.Count > 0)
   {
      string msg = (string)thisQueue.Dequeue();
      // Do some more...
    }
    // ....
}

How I am trying to enqueue:

public void enqueueThis(string msg)
{
    thisQueue.Enqueue(msg);
}

P.S. I am calling the enqueueThis function from another object. In other words, outside the main thread and script.

test if you get errors when wrapping that inner while loop into try-catch.

i did same thing before, and then found out that queue is not thread safe… sometimes it failed on that .Count or was it .Dequeue.

Thanks for the reply @mgear !

I tried wrapping the while loop inside a try-catch (Exception ex) and did not get any errors. I tried with a simple Debug.LogException(ex). But, I can also note that I have another queue inside the thread and that one works fine. The other queue shouldn’t overlap with the one I am in desperate need of help with either.

It’s just that I feel completely stuck on what I am asking about here. It doesn’t give any errors or anything. The queue simply doesn’t want to enqueue “properly” since when I am checking for thisQueue.Count > 0 inside the thread loop, it won’t return anything.

Any other ideas? I can post some more of my code if that would bring insight.

We’ll need to see some more code but here are a few guesses:

  • Your thisQueue field is a local variable or other thread specific variable.
  • You instantiate two instances of your class and have the threads using different instances from eachother.

Also…
Unless you are using a thread safe version of a queue, you’ll need to lock around the queue, dequeue and count calls. If you don’t, you’ll still get interaction but the data will probably become corrupt at some point.

Using exception handlers here won’t really help you since, first of all, it seems the two threads are using two different queues, and secondly, failing cooperative parallelization rarely throws exceptions by default. You just get corrupted data which you could try to detect and throw yourself.

Let’s see some more code from this class and we’ll get to the bottom of your trouble.