-1

Do the glibc implementation of pthread_spin_lock() and pthread_spin_unlock() function have memory fence instructions? (I could not find any fence instructions.)

Similar question has answers here. Does pthread_mutex_lock contains memory fence instruction?

Hiro Yoshioka
  • 29
  • 1
  • 5

1 Answers1

2

Do the glibc implementation of pthread_spin_lock() and pthread_spin_unlock() function have memory fence instructions?

There is no the implementation -- there is an implementation for each supported processor.

The x86_64 implementation does not use memory fences; it uses lock prefix instead:

gdb -q /lib/x86_64-linux-gnu/libpthread.so.0

(gdb) disas pthread_spin_lock
Dump of assembler code for function pthread_spin_lock:
   0x00000000000108c0 <+0>:     lock decl (%rdi)
   0x00000000000108c3 <+3>:     jne    0x108d0 <pthread_spin_lock+16>
   0x00000000000108c5 <+5>:     xor    %eax,%eax
   0x00000000000108c7 <+7>:     retq   
   0x00000000000108c8 <+8>:     nopl   0x0(%rax,%rax,1)
   0x00000000000108d0 <+16>:    pause  
   0x00000000000108d2 <+18>:    cmpl   $0x0,(%rdi)
   0x00000000000108d5 <+21>:    jg     0x108c0 <pthread_spin_lock>
   0x00000000000108d7 <+23>:    jmp    0x108d0 <pthread_spin_lock+16>

Since lock-prefixed instructions are already a memory barrier on x86_64 (and i386), no additional memory barriers are necessary.

But powerpc implementation uses lwarx and stwcx instructions, which are closer to "memory fence", and sparc64 implementation uses full membar (memory barrier) instruction.

You can see the various implementations in sysdeps/.../pthread_spin_lock.* files in GLIBC sources.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • 1
    It is worth pointing out that the x86_64 implementation does not need memory fences, because x86 locked instructions are a barrier. – caf Dec 14 '20 at 02:58