Hacker News new | ask | show | jobs
by wuch 3250 days ago
In case someone is interested, here is relevant code [0]. Notice that mutexp is read without any synchronization, and _spinlock further down uses different lock than one in initialization code (former is specific to this mutex and latter a global one). There is no happens before relationship between mutex initialization and mutex locking. Thus, if different thread reads non-null value of *mutexp, there is no guarantee that writes done to the mutext structure itself will be visible. Given strong memory model of amd64 and i386, compiler would have to reorder pointer publication and structure initialization in pthread_mutex_init, unlikely but certainly a valid change given lack of synchronization.

[0] https://github.com/openbsd/src/blob/0ecb71b5ec9e4b22a484606f...

1 comments

Correct me if I'm wrong, but I think a compiler that doesn't do link-time-optimization has to assume that the _spinlock() function can write to mutexp (e.g. through a global variable), and therefore it cannot reorder anything around it.
I think you are looking at the side that does the reading. I was actually thinking about the other side that does the writing (inside pthread_mutex_init), where those two things are not separated by any function calls and are more readily reordered. Not to mention that it would be problematic on architectures with relaxed memory model either way.