summaryrefslogtreecommitdiff
path: root/sys/man/2/semacquire
blob: 0eb0fc97b0646a766d5ff27f6f32646386900528 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
.TH SEMACQUIRE 2
.SH NAME
semacquire, tsemacquire, semrelease - user level semaphores
.SH SYNOPSIS
.B #include <u.h>
.br
.B #include <libc.h>
.PP
.B
int semacquire(long *addr, int block);
.PP
.B
int tsemacquire(long *addr, ulong ms);
.PP
.B
long semrelease(long *addr, long count);
.SH DESCRIPTION
.IR Semacquire ,
.IR tsemacquire ,
and
.I semrelease
facilitate scheduling between processes sharing memory.
Processes arrange to share memory by using
.I rfork
with the
.B RFMEM
flag
(see
.IR fork (2)),
.IR segattach (2),
or
.IR thread (2).
.PP
The semaphore's value is the integer pointed at by
.IR addr .
.I Semacquire
atomically waits until the semaphore has a positive value
and then decrements that value.
If
.I block
is zero
and the semaphore is not immediately available,
.I semacquire
returns 0 instead of waiting.
.I Tsemacquire
only waits
.I ms
milliseconds for the semaphore to attain a positive value
and, if available in that time, decrements that value.
It returns 0 otherwise.
Both functions return 1 if the semaphore was acquired
and -1 on error
(e.g., if they were interrupted).
.I Semrelease
adds
.I count
to the semaphore's value
and returns the new value.
.PP
.I Semacquire
(and analogously for
.IR tsemacquire )
and
.I semrelease
can be thought of as efficient, correct replacements for:
.IP
.EX
int
semacquire(long *addr, int block)
{
	while(*addr == 0){
		if(!block)
			return 0;
		if(interrupted)
			return -1;
	}
	--*addr;
	return 1;
}

int
semrelease(long *addr, int count)
{
	return *addr += count;
}
.EE
.PP
Like
.IR rendezvous (2),
.IR semacquire ,
.IR tsemacquire ,
and
.I semrelease
are not typically used directly.
Instead, they are intended to be used to coordinate
scheduling in higher-level abstractions such as
locks, rendezvous points, and channels
(see
.IR lock (2)
and
.IR thread (2)).
Also like
.IR rendezvous ,
.IR semacquire ,
.IR tsemacquire ,
and
.I semrelease
cannot be used to coordinate between threads
in a single process.
Use locks, rendezvous points, or channels instead.
.SH SOURCE
.B /sys/src/9/port/sysproc.c
.SH SEE ALSO
.IR fork (2),
.IR lock (2),
.IR rendezvous (2),
.IR segattach (2),
.IR thread (2)
.SH DIAGNOSTICS
These functions set
.IR errstr .