/root/doris/be/src/util/spinlock.h
Line | Count | Source |
1 | | // Licensed to the Apache Software Foundation (ASF) under one |
2 | | // or more contributor license agreements. See the NOTICE file |
3 | | // distributed with this work for additional information |
4 | | // regarding copyright ownership. The ASF licenses this file |
5 | | // to you under the Apache License, Version 2.0 (the |
6 | | // "License"); you may not use this file except in compliance |
7 | | // with the License. You may obtain a copy of the License at |
8 | | // |
9 | | // http://www.apache.org/licenses/LICENSE-2.0 |
10 | | // |
11 | | // Unless required by applicable law or agreed to in writing, |
12 | | // software distributed under the License is distributed on an |
13 | | // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
14 | | // KIND, either express or implied. See the License for the |
15 | | // specific language governing permissions and limitations |
16 | | // under the License. |
17 | | // This file is copied from |
18 | | // https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/spinlock.h |
19 | | // and modified by Doris |
20 | | |
21 | | #pragma once |
22 | | |
23 | | #include <sched.h> /* For sched_yield() */ |
24 | | |
25 | | #include <atomic> |
26 | | |
27 | | namespace doris { |
28 | | |
29 | | // Lightweight spinlock. |
30 | | class SpinLock { |
31 | | public: |
32 | 6.40k | SpinLock() : _locked(false) { |
33 | | // do nothing |
34 | 6.40k | } |
35 | | |
36 | | // Acquires the lock, spins until the lock becomes available |
37 | 89.4k | void lock() { |
38 | 4.97M | for (int spin_count = 0; !try_lock(); ++spin_count) { |
39 | 4.88M | if (spin_count < NUM_SPIN_CYCLES) { |
40 | 4.21M | #if (defined(__i386) || defined(__x86_64__)) |
41 | 4.21M | asm volatile("pause\n" : : : "memory"); |
42 | | #elif defined(__aarch64__) |
43 | | asm volatile("yield\n" ::: "memory"); |
44 | | #endif |
45 | 4.21M | } else { |
46 | 671k | sched_yield(); |
47 | 671k | spin_count = 0; |
48 | 671k | } |
49 | 4.88M | } |
50 | 89.4k | } |
51 | | |
52 | 89.5k | void unlock() { _locked.clear(std::memory_order_release); } |
53 | | |
54 | | // Tries to acquire the lock |
55 | 3.99M | bool try_lock() { return !_locked.test_and_set(std::memory_order_acquire); } |
56 | | |
57 | | private: |
58 | | static const int NUM_SPIN_CYCLES = 70; |
59 | | std::atomic_flag _locked; |
60 | | }; |
61 | | |
62 | | } // end namespace doris |