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