1 #include "futex_impl.h"
2 #include "threads_impl.h"
3 #include "stdio_impl.h"
4 
__lockfile(FILE * f)5 int __lockfile(FILE* f) {
6     int owner, tid = __thread_get_tid();
7     if (atomic_load(&f->lock) == tid)
8         return 0;
9     while ((owner = a_cas_shim(&f->lock, 0, tid)))
10         __wait(&f->lock, &f->waiters, owner);
11     return 1;
12 }
13 
__unlockfile(FILE * f)14 void __unlockfile(FILE* f) {
15     atomic_store(&f->lock, 0);
16 
17     /* The following read is technically invalid under situations
18      * of self-synchronized destruction. Another thread may have
19      * called fclose as soon as the above store has completed.
20      * Nonetheless, since FILE objects always live in memory
21      * obtained by malloc from the heap, it's safe to assume
22      * the dereferences below will not fault. In the worst case,
23      * a spurious syscall will be made. If the implementation of
24      * malloc changes, this assumption needs revisiting. */
25 
26     if (atomic_load(&f->waiters))
27         _zx_futex_wake(&f->lock, 1);
28 }
29