1/*
2 * Copyright 2011 Google Inc. All Rights Reserved.
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#include "sfntly/port/lock.h"
18
19namespace sfntly {
20
21#if defined (WIN32)
22
23Lock::Lock() {
24  // The second parameter is the spin count, for short-held locks it avoid the
25  // contending thread from going to sleep which helps performance greatly.
26  ::InitializeCriticalSectionAndSpinCount(&os_lock_, 2000);
27}
28
29Lock::~Lock() {
30  ::DeleteCriticalSection(&os_lock_);
31}
32
33bool Lock::Try() {
34  if (::TryEnterCriticalSection(&os_lock_) != FALSE) {
35    return true;
36  }
37  return false;
38}
39
40void Lock::Acquire() {
41  ::EnterCriticalSection(&os_lock_);
42}
43
44void Lock::Unlock() {
45  ::LeaveCriticalSection(&os_lock_);
46}
47
48#else  // We assume it's pthread
49
50Lock::Lock() {
51  pthread_mutex_init(&os_lock_, NULL);
52}
53
54Lock::~Lock() {
55  pthread_mutex_destroy(&os_lock_);
56}
57
58bool Lock::Try() {
59  return (pthread_mutex_trylock(&os_lock_) == 0);
60}
61
62void Lock::Acquire() {
63  pthread_mutex_lock(&os_lock_);
64}
65
66void Lock::Unlock() {
67  pthread_mutex_unlock(&os_lock_);
68}
69
70#endif
71
72}  // namespace sfntly
73