What is the minimum X86 assembly needed for a spinlock -


to implement spinlock in assembly. here post solution came with. correct? know shorter one?

lock:

    mov ecx, 0 .loop:     xchg [eax], ecx     cmp ecx, 0     je .loop 

release:

    lock dec dword [eax] 

eax initialized -1 (which means lock free). should work many threads (not 2).

shortest be:

acquire:     lock bts [eax],0     jc acquire  release:     mov [eax],0 

for performance, it's best use "test, test , set" approach, , use pause, this:

acquire:     lock bts [eax],0    ;optimistic first attempt     jnc l2              ;success if acquired l1:     pause     test [eax],1             jne l1              ;don't attempt again unless there's chance      lock bts [eax],0    ;attempt acquire     jc l1               ;wait again if failed  l2:  release:     mov [eax],0 

for debugging, can add data make easier detect problems, this:

acquire:     lock bts [eax],31         ;optimistic first attempt     jnc l2                    ;success if acquired      mov ebx,[cpunumber]     lea ebx,[ebx+0x80000000]     cmp [eax],ebx             ;is lock acquired cpu?     je .bad                   ; yes, deadlock     lock inc dword [eax+4]    ;increase "lock contention counter" l1:     pause     test [eax],0x80000000             jne l1                    ;don't attempt again unless there's chance      lock bts [eax],31         ;attempt acquire     jc l1                     ;wait again if failed  l2: mov [eax],ebx             ;store cpu number  release:     mov ebx,[cpunumber]     lea ebx,[ebx+0x80000000]     cmp [eax],ebx             ;is lock acquired, , cpu same?     jne .bad                  ; no, either not acquired or wrong cpu     mov [eax],0 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -