]> git.proxmox.com Git - ceph.git/blob - ceph/src/include/Spinlock.h
update sources to v12.1.1
[ceph.git] / ceph / src / include / Spinlock.h
1 // -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
2 // vim: ts=8 sw=2 smarttab
3 /*
4 * Ceph - scalable distributed file system
5 *
6 * Copyright (C) 2013 Inktank
7 *
8 * This is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License version 2.1, as published by the Free Software
11 * Foundation. See file COPYING.
12 *
13 * @author Sage Weil <sage@inktank.com>
14 */
15
16 #ifndef CEPH_SPINLOCK_H
17 #define CEPH_SPINLOCK_H
18
19 #include "acconfig.h"
20
21 #include <pthread.h>
22
23 typedef struct {
24 #ifdef HAVE_PTHREAD_SPINLOCK
25 pthread_spinlock_t lock;
26 #else
27 pthread_mutex_t lock;
28 #endif
29 } ceph_spinlock_t;
30
31 #ifdef HAVE_PTHREAD_SPINLOCK
32
33 static inline int ceph_spin_init(ceph_spinlock_t *l)
34 {
35 return pthread_spin_init(&l->lock, PTHREAD_PROCESS_PRIVATE);
36 }
37
38 static inline int ceph_spin_destroy(ceph_spinlock_t *l)
39 {
40 return pthread_spin_destroy(&l->lock);
41 }
42
43 static inline int ceph_spin_lock(ceph_spinlock_t *l)
44 {
45 return pthread_spin_lock(&l->lock);
46 }
47
48 static inline int ceph_spin_unlock(ceph_spinlock_t *l)
49 {
50 return pthread_spin_unlock(&l->lock);
51 }
52
53 #else /* !HAVE_PTHREAD_SPINLOCK */
54
55 static inline int ceph_spin_init(ceph_spinlock_t *l)
56 {
57 return pthread_mutex_init(&l->lock, NULL);
58 }
59
60 static inline int ceph_spin_destroy(ceph_spinlock_t *l)
61 {
62 return pthread_mutex_destroy(&l->lock);
63 }
64
65 static inline int ceph_spin_lock(ceph_spinlock_t *l)
66 {
67 return pthread_mutex_lock(&l->lock);
68 }
69
70 static inline int ceph_spin_unlock(ceph_spinlock_t *l)
71 {
72 return pthread_mutex_unlock(&l->lock);
73 }
74
75 #endif
76
77 class Spinlock {
78 mutable ceph_spinlock_t _lock;
79
80 public:
81 Spinlock() {
82 ceph_spin_init(&_lock);
83 }
84 ~Spinlock() {
85 ceph_spin_destroy(&_lock);
86 }
87
88 // don't allow copying.
89 void operator=(Spinlock& s);
90 Spinlock(const Spinlock& s);
91
92 /// acquire spinlock
93 void lock() const {
94 ceph_spin_lock(&_lock);
95 }
96 /// release spinlock
97 void unlock() const {
98 ceph_spin_unlock(&_lock);
99 }
100
101 class Locker {
102 const Spinlock& spinlock;
103 public:
104 Locker(const Spinlock& s) : spinlock(s) {
105 spinlock.lock();
106 }
107 ~Locker() {
108 spinlock.unlock();
109 }
110 };
111 };
112
113 #endif