xref: /aosp_15_r20/external/llvm-libc/src/__support/threads/CndVar.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- A platform independent abstraction layer for cond vars --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC___SUPPORT_SRC_THREADS_LINUX_CNDVAR_H
10 #define LLVM_LIBC___SUPPORT_SRC_THREADS_LINUX_CNDVAR_H
11 
12 #include "src/__support/macros/config.h"
13 #include "src/__support/threads/linux/futex_utils.h" // Futex
14 #include "src/__support/threads/linux/raw_mutex.h"   // RawMutex
15 #include "src/__support/threads/mutex.h"             // Mutex
16 
17 #include <stdint.h> // uint32_t
18 
19 namespace LIBC_NAMESPACE_DECL {
20 
21 class CndVar {
22   enum CndWaiterStatus : uint32_t {
23     WS_Waiting = 0xE,
24     WS_Signalled = 0x5,
25   };
26 
27   struct CndWaiter {
28     Futex futex_word = WS_Waiting;
29     CndWaiter *next = nullptr;
30   };
31 
32   CndWaiter *waitq_front;
33   CndWaiter *waitq_back;
34   RawMutex qmtx;
35 
36 public:
init(CndVar * cv)37   LIBC_INLINE static int init(CndVar *cv) {
38     cv->waitq_front = cv->waitq_back = nullptr;
39     RawMutex::init(&cv->qmtx);
40     return 0;
41   }
42 
destroy(CndVar * cv)43   LIBC_INLINE static void destroy(CndVar *cv) {
44     cv->waitq_front = cv->waitq_back = nullptr;
45   }
46 
47   // Returns 0 on success, -1 on error.
48   int wait(Mutex *m);
49   void notify_one();
50   void broadcast();
51 };
52 
53 } // namespace LIBC_NAMESPACE_DECL
54 
55 #endif // LLVM_LIBC_SRC___SUPPORT_THREADS_LINUX_CNDVAR_H
56