blob: a36d1edd39f6ac4e96060d42aba0b5fa04cfd357 [file] [log] [blame]
Yabin Cui76615da2015-03-17 14:22:09 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28#ifndef _BIONIC_LOCK_H
29#define _BIONIC_LOCK_H
30
31#include <stdatomic.h>
32#include "private/bionic_futex.h"
33
Yabin Cuid26e7802015-10-22 20:07:56 -070034// Lock is used in places like pthread_rwlock_t, which can be initialized without calling
35// an initialization function. So make sure Lock can be initialized by setting its memory to 0.
Yabin Cui76615da2015-03-17 14:22:09 -070036class Lock {
37 private:
38 enum LockState {
39 Unlocked = 0,
40 LockedWithoutWaiter,
41 LockedWithWaiter,
42 };
43 _Atomic(LockState) state;
44 bool process_shared;
45
46 public:
Yabin Cui76615da2015-03-17 14:22:09 -070047 void init(bool process_shared) {
48 atomic_init(&state, Unlocked);
49 this->process_shared = process_shared;
50 }
51
52 void lock() {
53 LockState old_state = Unlocked;
54 if (__predict_true(atomic_compare_exchange_strong_explicit(&state, &old_state,
55 LockedWithoutWaiter, memory_order_acquire, memory_order_relaxed))) {
56 return;
57 }
58 while (atomic_exchange_explicit(&state, LockedWithWaiter, memory_order_acquire) != Unlocked) {
59 // TODO: As the critical section is brief, it is a better choice to spin a few times befor sleeping.
60 __futex_wait_ex(&state, process_shared, LockedWithWaiter, NULL);
61 }
62 return;
63 }
64
65 void unlock() {
66 if (atomic_exchange_explicit(&state, Unlocked, memory_order_release) == LockedWithWaiter) {
67 __futex_wake_ex(&state, process_shared, 1);
68 }
69 }
70};
71
72#endif // _BIONIC_LOCK_H