[gameprogrammer] Re: Single producer consumer

Bob, I don't follow your logic. Pointers are > 1 byte, therefore suppose 2 out of 4 bytes of the pointer were updated and a context switch occured. Then the pointer comparison would say the pointers are different, when in fact the update was in the middle of making them equal.

The crux of the issue is if a context switch can occur while in the middle of writing multiple bytes to a single variable.

If not, then what I have posted will work.

If so, then it won't work - however, the commented out code, if commented back in, will cause it to work. With the commented code, the pointers are volatile and so is a boolean value inside the data structure.

It's a double locking mechanism:

To finish a write:
Write the boolean true
Update the write pointer

Done reading:
Update the boolean false
Update the read pointer

To start reading:
Check if the boolean is true.
Check if the read pointer does not pass the write pointer.

Lets suppose somehow that the boolean was mid-write (4 bits)? and so had a corrupted value of true, when it should be false. The first pass (check if the boolean is true) would pass, however the second would not.

Lets suppose the write pointer was corrupted mid-write. Because the boolean is volatile, it is guaranteed to have been written immediately (and thus before the write pointer was written to). Therefore, the boolean check would be valid and the operation would be correct despite the pointer being invalid.

Or that is my logic at least.

Comments?


Bob Pendleton wrote:
On Thu, 2006-02-09 at 09:21 -0800, Kevin Jenkins wrote:

We're having a debate at work right now as to if you can write a thread-safe single producer consumer class without critical section locks. I claim you can, while another programmer claims you cannot. This is what I use:

http://www.rakkar.org/sourcecode/SingleProducerConsumer.h.txt

What I do is have two pointers - a write pointer and a read pointer. They cannot cross each other. Each pointer is only modified by one thread. Both threads compare these pointers using the == operator.

There are a few articles on google claiming correctly you cannot use a single shared pointer or index where both threads modify that variable, but none use my approach where I have two variables and each is only updated by its own thread.


I have used that technique in production code and it works great.
Better, it is provably correct. People get worried about the possibility
of comparing partially updated pointers. But, if you look at the range
of possible values for the pointers and the values that can be generated
by examining a partially updated multibyte pointer you see that this is
not a problem.

                Bob Pendleton


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html





---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: