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
8
#include "
user/common/syscalls.h
"
9
#include "
user/common/thread.h
"
10
11
int
mtx_lock
(
mtx_t
*
mutex
)
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
;
23
if
(
atomic_compare_exchange_strong
(&(
mutex
->
state
), &expected,
_MTX_LOCKED
))
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
;
35
if
(
atomic_compare_exchange_strong
(&(
mutex
->
state
), &expected,
_MTX_LOCKED
))
36
{
37
mutex
->
owner
= self;
38
mutex
->
depth
= 1;
39
return
thrd_success
;
40
}
41
42
if
(expected ==
_MTX_LOCKED
)
43
{
44
atomic_compare_exchange_strong
(&(
mutex
->
state
), &expected,
_MTX_CONTESTED
);
45
}
46
futex
(&(
mutex
->
state
),
_MTX_CONTESTED
,
FUTEX_WAIT
,
CLOCKS_NEVER
);
47
}
while
(1);
48
}
CLOCKS_NEVER
#define CLOCKS_NEVER
Definition
clock_t.h:16
gettid
tid_t gettid(void)
System call to retrieve the current tid.
Definition
gettid.c:6
futex
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
@ FUTEX_WAIT
The futex operating for waiting until the value pointed to by addr is not equal to val.
Definition
proc.h:227
tid_t
__UINT64_TYPE__ tid_t
Thread Identifier.
Definition
tid_t.h:12
mutex
static mtx_t mutex
Definition
heap.c:35
mtx_lock
int mtx_lock(mtx_t *mutex)
Definition
mtx_lock.c:11
proc.h
syscalls.h
thread.h
_MTX_SPIN_COUNT
#define _MTX_SPIN_COUNT
Definition
thread.h:10
stdatomic.h
atomic_compare_exchange_strong
#define atomic_compare_exchange_strong(object, expected, desired)
Definition
stdatomic.h:278
stdbool.h
uint64_t
__UINT64_TYPE__ uint64_t
Definition
stdint.h:17
stdio.h
stdlib.h
mtx_t
Definition
threads.h:52
mtx_t::owner
tid_t owner
Definition
threads.h:54
mtx_t::depth
uint64_t depth
Definition
threads.h:55
mtx_t::state
atomic_uint64_t state
Definition
threads.h:53
threads.h
_MTX_UNLOCKED
#define _MTX_UNLOCKED
Definition
threads.h:47
_MTX_CONTESTED
#define _MTX_CONTESTED
Definition
threads.h:49
thrd_success
@ thrd_success
Definition
threads.h:74
_MTX_LOCKED
#define _MTX_LOCKED
Definition
threads.h:48
src
libstd
user
functions
thread
mtx_lock.c
Generated by
1.9.8