xref: /haiku/src/libs/compat/freebsd_network/condvar.cpp (revision 52f7c9389475e19fc21487b38064b4390eeb6fea)
1 /*
2  * Copyright 2022, Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT license.
4  */
5 
6 extern "C" {
7 #include <compat/sys/mutex.h>
8 #include <compat/sys/kernel.h>
9 }
10 
11 #include <compat/sys/condvar.h>
12 
13 
14 void
15 cv_init(struct cv* variable, const char* description)
16 {
17 	variable->condition.Init(NULL, description);
18 }
19 
20 
21 void
22 cv_destroy(struct cv* variable)
23 {
24 	variable->condition.NotifyAll();
25 	// Nothing else to do.
26 }
27 
28 
29 void
30 cv_signal(struct cv* variable)
31 {
32 	variable->condition.NotifyOne();
33 }
34 
35 
36 int
37 cv_timedwait(struct cv* variable, struct mtx* mutex, int timeout)
38 {
39 	int status;
40 
41 	const uint32 flags = timeout ? B_RELATIVE_TIMEOUT : 0;
42 	const bigtime_t bigtimeout = TICKS_2_USEC(timeout);
43 
44 	if (mutex->type == MTX_RECURSE) {
45 		// Special case: let the ConditionVariable handle switching recursive locks.
46 		status = variable->condition.Wait(&mutex->u.recursive,
47 			flags, bigtimeout);
48 		return status;
49 	}
50 
51 	ConditionVariableEntry entry;
52 	variable->condition.Add(&entry);
53 
54 	mtx_unlock(mutex);
55 
56 	status = entry.Wait(flags, bigtimeout);
57 
58 	mtx_lock(mutex);
59 	return status;
60 }
61 
62 
63 void
64 cv_wait(struct cv* variable, struct mtx* mutex)
65 {
66 	cv_timedwait(variable, mutex, 0);
67 }
68