This is the mail archive of the glibc-bugs@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug nptl/16432] pthread_spin_unlock should imply a memory barrier


https://sourceware.org/bugzilla/show_bug.cgi?id=16432

--- Comment #6 from Mikulas Patocka <mikulas at artax dot karlin.mff.cuni.cz> ---
Another example, see this:

#include <stdatomic.h>
#include <stdlib.h>
#include <string.h>

struct s {
        char str[100];
};

struct s * _Atomic ptr = NULL;

void fn(void)
{
        struct s *s = malloc(sizeof(struct s));
        strcpy(s->str, "Hello World!");
        atomic_store_explicit(&ptr, s, __ATOMIC_SEQ_CST);
}

... according to the C11 standard, the strcpy instruction uses non-atomic
memory accesses, so it doesn't synchronize with the "atomic_store_explicit"
statement. So, the compiler can well move the "strcpy" call after
"atomic_store_explicit" and the other thread that reads the pointer will see
uninitialized memory in the field "str".

So, to use the C11 memory model correctly, you can't even use library functions
that reference memory. You have to write your own function for copying strings:
_Atomic char *atomic_strcpy(_Atomic char *dst, _Atomic char *src)
{
        size_t idx = 0;
        char c;
        do {
                c = atomic_load_explicit(&src[idx], __ATOMIC_RELAXED);
                atomic_store_explicit(&dst[idx], c, __ATOMIC_RELAXED);
                idx++;
        } while (c);
        return dst;
}

I wish someone explained these problems to the committee and made them change
the standard so that atomic operations (except __ATOMIC_RELAXED) work like real
barriers and synchronize with all memory accesses, atomic or not. That would
make the standard much more useable.

-- 
You are receiving this mail because:
You are on the CC list for the bug.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]