On Sun, Feb 16, 2003 at 10:15:51AM +0100, Frank A. Uepping wrote: > Hi, > when I have a circular buffer like: > struct circular_buf { > char buf[]; > volatile int head, tail; > }; > > And I have one producer and one consumer. > The producer modifies the head and reads tail. > The consumer modifies the tail and reads head. > Producer and consumer are executed in different threads. > Is it sufficient to qualify head and tail with volatile or is some > kind of locking needed? The volatile keyword only tells the compiler: please load this variable everytime you read it, cause it might have been changed by an external source. It doesn't tell *anything* about writing to that variable. Suppose you have a variable i that tells you how many elements are in the buffer. What could happen without proper locking is: consumer thread producer thread value of i, j, and k -------------------------------------------------------------------- thread starts 1, undef, undef j = i 1, 1, undef j-- 1, 0, undef thread interrupted thread starts k = i 1, 0, 1 k++ 1, 0, 2 thread continues thread interrupted i = j 0, 0, 2 thread ends thread continues i = k 2, undef, 2 So it looks like there are two elements in the buffer, while there is only one. With proper locking of variable i, this wouldn't have happened. Erik -- J.A.K. (Erik) Mouw Email: J.A.K.Mouw@its.tudelft.nl mouw@nl.linux.org
Attachment:
pgp00305.pgp
Description: PGP signature