Possible Bug in threading (Episode 124)

Hello All,

I was watching episode 124 and i think i ahve spotted a possible bug in the threading code.

The loop in the thread reads as follows:

1
2
3
4
  if(NextEntryToDo < EntryCount)
        {
            uint32 EntryIndex = InterlockedIncrement((LONG volatile *)&NextEntryToDo) - 1;
            CompletePastReadsBeforeFutureReads;


So now the InterlockedIncrement will amke sure we always get a unique number, but the way i read it, 2 threads could reach that (As both see NextEntryToDo < EntryCount) so now, it could happen that we get a number that is further along then that we have written (EntryIndex could be > EntryCount). I tested this by removing the semaphore and putting some sleeps in the filling of the queue and got it to fetch to far ahead.

So i think we either need to check if EntryIndex <= Entrycount (and if it is we might need to decrement the Index? Or do something smart), or find a smarter way to do the if.

Is this indeed a bug or am i thinking of this all wrong?

Regards,

Robert

Edited by robert on
Awesome catch! Yes I think that is a bug. This probably serves me write for violating my own rule that I said at the beginning which was to just use InterlockedCompareExchange :P

We'll take care of it tomorrow.

- Casey