aboutsummaryrefslogtreecommitdiff
path: root/src/lib9/lock.c
blob: e97b967f2076b2a9abdf07db6143571cd29d3ebe (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <u.h>
#include <unistd.h>
#include <sched.h>
#include <libc.h>

int _ntas;
static int
_xtas(void *v)
{
	int x;

	_ntas++;
	x = _tas(v);
	return x;
}

int
canlock(Lock *l)
{
	return !_xtas(&l->val);
}

void
unlock(Lock *l)
{
	l->val = 0;
}

void
lock(Lock *lk)
{
	int i;

	/* once fast */
	if(!_xtas(&lk->val))
		return;
	/* a thousand times pretty fast */
	for(i=0; i<1000; i++){
		if(!_xtas(&lk->val))
			return;
		sched_yield();
	}
	/* now nice and slow */
	for(i=0; i<1000; i++){
		if(!_xtas(&lk->val))
			return;
		usleep(100*1000);
	}
	/* take your time */
	while(_xtas(&lk->val))
		usleep(1000*1000);
}