File: mtx_trylock.c

package info (click to toggle)
dietlibc 0.34~cvs20160606-10
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 11,336 kB
  • sloc: ansic: 71,631; asm: 13,006; cpp: 1,860; makefile: 799; sh: 292; perl: 62
file content (28 lines) | stat: -rw-r--r-- 700 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#define _REENTRANT
#define _DIETLIBC_SOURCE
#include <threads.h>
#include <sys/futex.h>
#include <errno.h>

int __mtx_trylock(mtx_t* mutex,int* lockval) {
  int i;
  thrd_t me=thrd_current();
  /* attempt to lock the mutex with an atomic instruction */
  if ((i=__sync_val_compare_and_swap(&mutex->lock,0,1))==0) {
    mutex->owner=me;
    return thrd_success;
  }
  if ((mutex->type&mtx_recursive) && mutex->owner==me) {
    if (__sync_add_and_fetch(&mutex->lock,1)>1000) {
      __sync_add_and_fetch(&mutex->lock,-1);
      return thrd_error;
    }
    return thrd_success;
  }
  if (lockval) *lockval=i;
  return thrd_busy;
}

int mtx_trylock(mtx_t* mutex) {
  return __mtx_trylock(mutex,NULL);
}