PatchworkOS
Loading...
Searching...
No Matches
mtx_lock.c
Go to the documentation of this file.
1#include <stdatomic.h>
2#include <stdbool.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <sys/proc.h>
6#include <threads.h>
7
10
12{
13 tid_t self = gettid();
14 if (mutex->owner == self)
15 {
16 mutex->depth++;
17 return thrd_success;
18 }
19
20 for (uint64_t i = 0; i < _MTX_SPIN_COUNT; i++)
21 {
22 uint64_t expected = _MTX_UNLOCKED;
24 {
25 mutex->owner = self;
26 mutex->depth = 1;
27 return thrd_success;
28 }
29 asm volatile("pause");
30 }
31
32 do
33 {
34 uint64_t expected = _MTX_UNLOCKED;
36 {
37 mutex->owner = self;
38 mutex->depth = 1;
39 return thrd_success;
40 }
41
42 if (expected == _MTX_LOCKED)
43 {
45 }
47 } while (1);
48}
#define CLOCKS_NEVER
Definition clock_t.h:16
tid_t gettid(void)
System call to retrieve the current tid.
Definition gettid.c:6
uint64_t futex(atomic_uint64_t *addr, uint64_t val, futex_op_t op, clock_t timeout)
System call for fast user space mutual exclusion.
Definition futex.c:6
@ FUTEX_WAIT
The futex operating for waiting until the value pointed to by addr is not equal to val.
Definition proc.h:227
__UINT64_TYPE__ tid_t
Thread Identifier.
Definition tid_t.h:12
static mtx_t mutex
Definition heap.c:35
int mtx_lock(mtx_t *mutex)
Definition mtx_lock.c:11
#define _MTX_SPIN_COUNT
Definition thread.h:10
#define atomic_compare_exchange_strong(object, expected, desired)
Definition stdatomic.h:278
__UINT64_TYPE__ uint64_t
Definition stdint.h:17
tid_t owner
Definition threads.h:54
uint64_t depth
Definition threads.h:55
atomic_uint64_t state
Definition threads.h:53
#define _MTX_UNLOCKED
Definition threads.h:47
#define _MTX_CONTESTED
Definition threads.h:49
@ thrd_success
Definition threads.h:74
#define _MTX_LOCKED
Definition threads.h:48