xref: /third_party/musl/src/stdio/__lockfile.c (revision 570af302)
1#include "stdio_impl.h"
2#include "pthread_impl.h"
3
4int __lockfile(FILE *f)
5{
6	int owner = f->lock, tid = __pthread_self()->tid;
7	if ((owner & ~MAYBE_WAITERS) == tid)
8		return 0;
9	owner = a_cas(&f->lock, 0, tid);
10	if (!owner) return 1;
11	while ((owner = a_cas(&f->lock, 0, tid|MAYBE_WAITERS))) {
12		if ((owner & MAYBE_WAITERS) ||
13		    a_cas(&f->lock, owner, owner|MAYBE_WAITERS)==owner)
14			__futexwait(&f->lock, owner|MAYBE_WAITERS, 1);
15	}
16	return 1;
17}
18
19void __unlockfile(FILE *f)
20{
21	if (a_swap(&f->lock, 0) & MAYBE_WAITERS)
22		__wake(&f->lock, 1, 1);
23}
24