Line data Source code
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 :
19 : namespace sfntly {
20 :
21 : #if defined (WIN32)
22 :
23 : Lock::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 :
29 : Lock::~Lock() {
30 : ::DeleteCriticalSection(&os_lock_);
31 : }
32 :
33 : bool Lock::Try() {
34 : if (::TryEnterCriticalSection(&os_lock_) != FALSE) {
35 : return true;
36 : }
37 : return false;
38 : }
39 :
40 : void Lock::Acquire() {
41 : ::EnterCriticalSection(&os_lock_);
42 : }
43 :
44 : void Lock::Unlock() {
45 : ::LeaveCriticalSection(&os_lock_);
46 : }
47 :
48 : #else // We assume it's pthread
49 :
50 0 : Lock::Lock() {
51 0 : pthread_mutex_init(&os_lock_, NULL);
52 0 : }
53 :
54 0 : Lock::~Lock() {
55 0 : pthread_mutex_destroy(&os_lock_);
56 0 : }
57 :
58 0 : bool Lock::Try() {
59 0 : return (pthread_mutex_trylock(&os_lock_) == 0);
60 : }
61 :
62 0 : void Lock::Acquire() {
63 0 : pthread_mutex_lock(&os_lock_);
64 0 : }
65 :
66 0 : void Lock::Unlock() {
67 0 : pthread_mutex_unlock(&os_lock_);
68 0 : }
69 :
70 : #endif
71 :
72 : } // namespace sfntly
|