Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: GCC inline asm. Interesting notes, particularly about atomic locks.

Author: Matt Taylor

Date: 22:35:08 12/20/02

Go up one level in this thread


On December 20, 2002 at 16:30:20, Dezhi Zhao wrote:

>On December 19, 2002 at 11:40:11, Robert Hyatt wrote:
>
>>For those remembering the discussion from a couple of weeks ago, I
>>had run into a strange problem with getting an inline asm lock to
>>work.  I was playing with this because I was following the Intel
>>guideline of adding a "pause" to the "shadow-lock" part of the code.
>>
>>First, the inline asm code:
>>
>>void static __inline__ LockX86(volatile int * lock) {
>>        int dummy;
>>        asm __volatile__ (
>>            "1:          movl    $1, %0"           "\n\t"
>>            "            xchgl   (%1), %0"         "\n\t"
>>            "            testl   %0, %0"           "\n\t"
>>            "            jz      3f"               "\n\t"
>>            "2:          pause"                    "\n\t"
>>            "            movl    (%1), %0"         "\n\t"
>>            "            testl   %0, %0"           "\n\t"
>> ****       "            jnz     2b"               "\n\t"
>>            "            jmp     1b"               "\n\t"
>>            "3:"                                   "\n\t"
>>            : "=&q" (dummy)
>>            : "q" (lock)
>>            : "cc");
>>}
>>
>
>Can we safely delete xchgl (%1), %0 instruction here? There is a similar example
>in the Intel spin lock application note. However the Intel example goes without
>an xchg instruction.

If you delete the xchg, how do you intend to avoid race conditions?

The lock is "held" when its contents are non-zero. The exchange part of this
writes a non-zero value to the lock and reads the previous lock value
atomically. If the previous value was non-zero, the lock was already held, and
because it's a shadow lock, you poll until it becomes free. That's when you try
and grab it again with the exchange. If someone else beat you, you'll have to
poll again before making another exchange.

If you delete the exchange, you'll never write a non-zero value to the lock.

-Matt



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.