inital commit
[c11concurrency-benchmarks.git] / mabain / src / lock.h
1 /**
2  * Copyright (C) 2017 Cisco Inc.
3  *
4  * This program is free software: you can redistribute it and/or  modify
5  * it under the terms of the GNU General Public License, version 2,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  */
16
17 // @author Changxue Deng <chadeng@cisco.com>
18
19 #ifndef __LOCK_H__
20 #define __LOCK_H__
21
22 #include <pthread.h>
23
24 namespace mabain {
25
26 // multiple-thread/process reader/writer lock
27
28 class MBLock
29 {
30 public:
31     MBLock();
32     ~MBLock();
33
34     // Writer lock
35     inline int WrLock();
36     // Reader lock
37     inline int RdLock();
38     // Writer/reader unlock
39     inline int UnLock();
40
41     inline int TryWrLock();
42
43     void Init(pthread_rwlock_t *rw_lock);
44
45 private:
46     // a global lock variable
47     static pthread_rwlock_t mb_rw_lock;
48
49     pthread_rwlock_t *mb_rw_lock_ptr;
50 };
51
52 inline int MBLock::WrLock()
53 {
54     if(mb_rw_lock_ptr == NULL)
55         return -1;
56     return pthread_rwlock_wrlock(mb_rw_lock_ptr);
57 }
58
59 inline int MBLock::RdLock()
60 {
61     if(mb_rw_lock_ptr == NULL)
62         return -1;
63     return pthread_rwlock_rdlock(mb_rw_lock_ptr);
64 }
65
66 inline int MBLock::UnLock()
67 {
68     if(mb_rw_lock_ptr == NULL)
69         return -1;
70     return pthread_rwlock_unlock(mb_rw_lock_ptr);
71 }
72
73 inline int MBLock::TryWrLock()
74 {
75     if(mb_rw_lock_ptr == NULL)
76         return -1;
77     return pthread_rwlock_trywrlock(mb_rw_lock_ptr);
78 }
79
80 }
81
82 #endif