-
Notifications
You must be signed in to change notification settings - Fork 10
/
spin_lock.hpp
59 lines (51 loc) · 1.73 KB
/
spin_lock.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Copyright (C) 2018 Dean De Leo, email: dleo[at]cwi.nl
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef PMA_SPIN_LOCK_HPP_
#define PMA_SPIN_LOCK_HPP_
#include <cassert>
#include <iostream>
#include <pthread.h>
#include "errorhandling.hpp"
class SpinLock {
pthread_spinlock_t m_lock;
public:
SpinLock(){
int rc = pthread_spin_init(&m_lock, PTHREAD_PROCESS_PRIVATE);
if(rc != 0){ RAISE_EXCEPTION(Exception, "Cannot initialise the spin lock: " << (rc);) }
}
~SpinLock(){
int rc = pthread_spin_destroy(&m_lock);
if(rc != 0){ std::cerr << "[ERROR] Cannot destroy the spin lock: " << rc << std::endl; }
}
void lock(){
#if !defined(NDEBUG)
int rc = pthread_spin_lock(&m_lock);
assert(rc == 0 && "Cannot acquire the spin lock");
#else
/* ignore the return code */ pthread_spin_lock(&m_lock);
#endif
}
void unlock(){
#if !defined(NDEBUG)
int rc = pthread_spin_unlock(&m_lock);
assert(rc == 0 && "Cannot release the spin lock");
#else
/* ignore the return code */ pthread_spin_unlock(&m_lock);
#endif
}
};
#endif /* PMA_SPIN_LOCK_HPP_ */