xref: /openbsd/share/man/man9/cond_init.9 (revision 4bdff4be)
1.\"	$OpenBSD: cond_init.9,v 1.3 2022/03/11 14:42:08 visa Exp $ */
2.\"
3.\" Copyright (c) 2017 David Gwynne <dlg@openbsd.org>
4.\"
5.\" Permission to use, copy, modify, and distribute this software for any
6.\" purpose with or without fee is hereby granted, provided that the above
7.\" copyright notice and this permission notice appear in all copies.
8.\"
9.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12.\" ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14.\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15.\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16.\"
17.Dd $Mdocdate: March 11 2022 $
18.Dt COND_INIT 9
19.Os
20.Sh NAME
21.Nm cond_init ,
22.Nm cond_wait ,
23.Nm cond_signal ,
24.Nm COND_INITIALIZER
25.Nd wait condition API
26.Sh SYNOPSIS
27.In sys/systm.h
28.Ft void
29.Fn "cond_init" "struct cond *c"
30.Ft void
31.Fn "cond_wait" "struct cond *c" "const char *wmesg"
32.Ft void
33.Fn "cond_signal" "struct cond *c"
34.Fn "COND_INITIALIZER"
35.Sh DESCRIPTION
36The wait condition API allows a thread to sleep while it waits for
37a notification, aka signal, that pending work has completed.
38.Pp
39.Fn cond_init
40initialises the wait condition
41.Fa c
42for use.
43.Pp
44.Fn cond_wait
45is used to sleep on the wait condition
46.Fa c
47until whatever the thread is waiting on calls
48.Fn cond_signal .
49.Fa wmesg
50is a pointer to a character string indicating the reason the thread
51is sleeping.
52.Pp
53.Fn cond_signal
54is used to notify the thread waiting on
55.Fa c
56that the work has finished and it may proceed.
57.Pp
58.Fn COND_INITIALIZER
59initialises a declaration of a cond for use.
60.Sh CONTEXT
61.Fn cond_init ,
62and
63.Fn cond_signal
64can be called during autoconf, from process context, or from interrupt
65context.
66.Pp
67.Fn cond_wait
68can be called from process context.
69.Sh EXAMPLES
70.Xr taskq_barrier 9
71is implemented using the wait condition API.
72The following is a commented copy of the implementation:
73.Bd -literal
74static void	taskq_barrier_task(void *);
75
76void
77taskq_barrier(struct taskq *tq)
78{
79	struct cond c;
80	struct task t;
81
82	/*
83	 * any currently running work has to have finished
84	 * before this new task can be run.
85	 */
86
87	cond_init(&c);
88	task_init(&t, taskq_barrier_task, &c);
89
90	task_add(tq, &t);
91
92	/* wait until the task runs and signals completion */
93	cond_wait(&c, "tqbar");
94}
95
96static void
97taskq_barrier_task(void *p)
98{
99	struct cond *c = p;
100
101	/*
102	 * all previous tasks have run, signal the thread waiting
103	 * in taskq_barrier
104	 */
105
106	cond_signal(c);
107}
108.Ed
109