1

I know that when I use pthread_create() an appropriate memory barrier is automatically issued so the new thread is guaranteed to see all the writes made by the parent thread up until its creation.

However, what if I use clone() manually on Linux? Should I include a full barrier myself, or will the kernel/glibc take care of that for me?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
ilstam
  • 1,473
  • 4
  • 18
  • 32
  • A system call can be considered as memory barrier – AlexStepanov May 16 '20 at 13:05
  • 2
    As a non-inline function call, `clone()` is effectively a compiler barrier. It's also as much of a barrier as whatever the kernel does internally, which I assume includes release-acquire sync with whatever core could be running the new thread. The only possible way for this to go wrong is if the other core only uses `mo_consume` style dependency ordering, like Linux uses in RCU under very carefully controlled conditions. I'm pretty sure you don't need an extra barrier. – Peter Cordes May 16 '20 at 13:07
  • @PeterCordes In the age of link-time optimization, is it still true in general that non-inline function calls are always full compiler barriers? (I do believe that `clone` in particular is, but only because it uses inline asm with a memory clobber.) – Joseph Sible-Reinstate Monica May 16 '20 at 20:58
  • 1
    @JosephSible-ReinstateMonica: Shared-library functions can't LTO inline into executables. And for Glibc specifically, you can't safely build an LTO-enabled static `libc.a`; [glibc's internals aren't LTO-safe](//stackoverflow.com/posts/comments/101802872). If it did inline, it wouldn't be a non-inline function call... I meant not inlined in the asm, not merely defined in a separate C source file. Also, the eventual `syscall` wrapper is either hand-written in asm and thus impossible to inline, or an inline `asm` statement with a `"memory"` clobber (a compiler barrier) in any non-buggy libc. – Peter Cordes May 16 '20 at 21:15
  • @JosephSible-ReinstateMonica Even if a call to a non `inline` function ends up being inlined, and thus is not a compiler barrier *in itself*, unless the function is pure calculations, it will involve some kind of switch to kernel mode, assembly code, or other unintelligible stuff that will certainly make the compiler put all externally accessible objects in their canonical representation as prescribed by the ABI. – curiousguy Aug 15 '20 at 18:54

0 Answers0