1#include "threads_impl.h"
2#include "stdio_impl.h"
3#include <limits.h>
4
5int ftrylockfile(FILE* f) {
6    int tid = __thread_get_tid();
7    if (f->lock == tid) {
8        if (f->lockcount == LONG_MAX)
9            return -1;
10        f->lockcount++;
11        return 0;
12    }
13    if (atomic_load(&f->lock) < 0)
14        atomic_store(&f->lock, 0);
15    if (atomic_load(&f->lock) || a_cas_shim(&f->lock, 0, tid))
16        return -1;
17    f->lockcount = 1;
18    return 0;
19}
20