blob: b02ed6173beecc2d8b0cdbc4ddfc194c279bc447 [file] [log] [blame]
Elliott Hughese8052e42018-07-13 13:06:08 -07001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19// TODO: switch to <mutex> and std::mutex when this code no longer needs
20// to compile for pre-C++11...
21
22#include <sys/types.h>
23
24#if !defined(_WIN32)
25#include <pthread.h>
26#else
27#include <windows.h>
28#endif
29
30#ifdef __cplusplus
31extern "C" {
32#endif
33
34#if !defined(_WIN32)
35
36typedef pthread_mutex_t mutex_t;
37
38static __inline__ void mutex_lock(mutex_t* lock) {
39 pthread_mutex_lock(lock);
40}
41
42static __inline__ void mutex_unlock(mutex_t* lock) {
43 pthread_mutex_unlock(lock);
44}
45
46static __inline__ int mutex_init(mutex_t* lock) {
Elliott Hughes952c1ee2018-07-13 19:59:57 -070047 return pthread_mutex_init(lock, NULL);
Elliott Hughese8052e42018-07-13 13:06:08 -070048}
49
50static __inline__ void mutex_destroy(mutex_t* lock) {
51 pthread_mutex_destroy(lock);
52}
53
54#else // !defined(_WIN32)
55
56typedef struct {
57 int init;
58 CRITICAL_SECTION lock[1];
59} mutex_t;
60
61#define MUTEX_INITIALIZER { 0, {{ NULL, 0, 0, NULL, NULL, 0 }} }
62
63static __inline__ void mutex_lock(mutex_t* lock) {
64 if (!lock->init) {
65 lock->init = 1;
66 InitializeCriticalSection( lock->lock );
67 lock->init = 2;
68 } else while (lock->init != 2) {
69 Sleep(10);
70 }
71 EnterCriticalSection(lock->lock);
72}
73
74static __inline__ void mutex_unlock(mutex_t* lock) {
75 LeaveCriticalSection(lock->lock);
76}
77
78static __inline__ int mutex_init(mutex_t* lock) {
79 InitializeCriticalSection(lock->lock);
80 lock->init = 2;
81 return 0;
82}
83
84static __inline__ void mutex_destroy(mutex_t* lock) {
85 if (lock->init) {
86 lock->init = 0;
87 DeleteCriticalSection(lock->lock);
88 }
89}
90
91#endif // !defined(_WIN32)
92
93#ifdef __cplusplus
94}
95#endif