__lockfile.c 830 B

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