Impala
Impalaistheopensource,nativeanalyticdatabaseforApacheHadoop.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
spinlock.h
Go to the documentation of this file.
1 // Copyright 2013 Cloudera Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef IMPALA_UTIL_SPINLOCK_H
16 #define IMPALA_UTIL_SPINLOCK_H
17 
18 #include "common/atomic.h"
19 #include "common/logging.h"
20 
21 namespace impala {
22 
24 class SpinLock {
25  public:
26  SpinLock() : locked_(false) {}
27 
29  void lock() {
30  if (!try_lock()) SlowAcquire();
31  }
32 
33  void unlock() {
34  // Memory barrier here. All updates before the unlock need to be made visible.
35  __sync_synchronize();
36  DCHECK(locked_);
37  locked_ = false;
38  }
39 
41  inline bool try_lock() { return __sync_bool_compare_and_swap(&locked_, false, true); }
42 
43  void DCheckLocked() { DCHECK(locked_); }
44 
45  private:
46 
50  void SlowAcquire();
51 
65  static const int NUM_SPIN_CYCLES = 70;
67  bool locked_;
68 };
69 
70 }
71 #endif
void SlowAcquire()
Definition: spinlock.cc:18
void DCheckLocked()
Definition: spinlock.h:43
Lightweight spinlock.
Definition: spinlock.h:24
bool locked_
TODO: pad this to be a cache line?
Definition: spinlock.h:67
void unlock()
Definition: spinlock.h:33
bool try_lock()
Tries to acquire the lock.
Definition: spinlock.h:41
void lock()
Acquires the lock, spins until the lock becomes available.
Definition: spinlock.h:29
static const int NUM_SPIN_CYCLES
Definition: spinlock.h:65