• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "include/base/internal/cef_lock_impl.h"
6 
7 #if defined(OS_WIN)
8 
9 namespace base {
10 namespace cef_internal {
11 
LockImpl()12 LockImpl::LockImpl() {
13   // The second parameter is the spin count, for short-held locks it avoid the
14   // contending thread from going to sleep which helps performance greatly.
15   ::InitializeCriticalSectionAndSpinCount(&native_handle_, 2000);
16 }
17 
~LockImpl()18 LockImpl::~LockImpl() {
19   ::DeleteCriticalSection(&native_handle_);
20 }
21 
Try()22 bool LockImpl::Try() {
23   if (::TryEnterCriticalSection(&native_handle_) != FALSE) {
24     return true;
25   }
26   return false;
27 }
28 
Lock()29 void LockImpl::Lock() {
30   ::EnterCriticalSection(&native_handle_);
31 }
32 
Unlock()33 void LockImpl::Unlock() {
34   ::LeaveCriticalSection(&native_handle_);
35 }
36 
37 }  // namespace cef_internal
38 }  // namespace base
39 
40 #elif defined(OS_POSIX)
41 
42 #include <errno.h>
43 #include <string.h>
44 
45 #include "include/base/cef_logging.h"
46 
47 namespace base {
48 namespace cef_internal {
49 
LockImpl()50 LockImpl::LockImpl() {
51 #if DCHECK_IS_ON()
52   // In debug, setup attributes for lock error checking.
53   pthread_mutexattr_t mta;
54   int rv = pthread_mutexattr_init(&mta);
55   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
56   rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
57   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
58   rv = pthread_mutex_init(&native_handle_, &mta);
59   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
60   rv = pthread_mutexattr_destroy(&mta);
61   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
62 #else
63   // In release, go with the default lock attributes.
64   pthread_mutex_init(&native_handle_, NULL);
65 #endif
66 }
67 
~LockImpl()68 LockImpl::~LockImpl() {
69   int rv = pthread_mutex_destroy(&native_handle_);
70   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
71 }
72 
Try()73 bool LockImpl::Try() {
74   int rv = pthread_mutex_trylock(&native_handle_);
75   DCHECK(rv == 0 || rv == EBUSY) << ". " << strerror(rv);
76   return rv == 0;
77 }
78 
Lock()79 void LockImpl::Lock() {
80   int rv = pthread_mutex_lock(&native_handle_);
81   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
82 }
83 
Unlock()84 void LockImpl::Unlock() {
85   int rv = pthread_mutex_unlock(&native_handle_);
86   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
87 }
88 
89 }  // namespace cef_internal
90 }  // namespace base
91 
92 #endif  // defined(OS_POSIX)
93