aboutsummaryrefslogtreecommitdiff
path: root/libc/src/__support/threads/CndVar.h
blob: 901b652c553d8313db2de2d270016d3234e3c8cf (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
//===-- A platform independent abstraction layer for cond vars --*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_LIBC___SUPPORT_SRC_THREADS_LINUX_CNDVAR_H
#define LLVM_LIBC___SUPPORT_SRC_THREADS_LINUX_CNDVAR_H

#include "hdr/stdint_proxy.h" // uint32_t
#include "src/__support/macros/config.h"
#include "src/__support/threads/linux/futex_utils.h" // Futex
#include "src/__support/threads/mutex.h"             // Mutex
#include "src/__support/threads/raw_mutex.h"         // RawMutex

namespace LIBC_NAMESPACE_DECL {

class CndVar {
  enum CndWaiterStatus : uint32_t {
    WS_Waiting = 0xE,
    WS_Signalled = 0x5,
  };

  struct CndWaiter {
    Futex futex_word = WS_Waiting;
    CndWaiter *next = nullptr;
  };

  CndWaiter *waitq_front;
  CndWaiter *waitq_back;
  RawMutex qmtx;

public:
  LIBC_INLINE static int init(CndVar *cv) {
    cv->waitq_front = cv->waitq_back = nullptr;
    RawMutex::init(&cv->qmtx);
    return 0;
  }

  LIBC_INLINE static void destroy(CndVar *cv) {
    cv->waitq_front = cv->waitq_back = nullptr;
  }

  // Returns 0 on success, -1 on error.
  int wait(Mutex *m);
  void notify_one();
  void broadcast();
};

} // namespace LIBC_NAMESPACE_DECL

#endif // LLVM_LIBC_SRC___SUPPORT_THREADS_LINUX_CNDVAR_H