1 #ifndef MUTEX_CLASS_H
2 #define MUTEX_CLASS_H
3
4 class mutex_class
5 {
6 public:
7 mutex_class();
8 void lock();
9 void unlock();
10
11 private:
12 //以下为使用,和一般的锁差不多
13 int MUTEX_VALUE;
14 };
15
16 #endif // MUTEX_CLASS_H
1 #include "mutex_class.h"
2 #include <sched.h>
3
4 #define LOCK_VALUE 0
5 #define UNLOCK_VALUE 1
6 //nt MUTEX_VALUE = LOCK_VALUE;
7 #define FREE_LOCK(MUTEX_VALUE_LOCK)\
8 while (!(__sync_bool_compare_and_swap (\
9 &MUTEX_VALUE_LOCK,LOCK_VALUE, \
10 UNLOCK_VALUE) )) \
11 sched_yield();
12
13 #define FREE_UNLOCK(MUTEX_VALUE_LOCK)\
14 __sync_bool_compare_and_swap (&MUTEX_VALUE_LOCK, UNLOCK_VALUE, LOCK_VALUE);
15
16
17
18
19 mutex_class::mutex_class()
20 {
21 MUTEX_VALUE = LOCK_VALUE;
22 }
23
24 void mutex_class::lock()
25 {
26 FREE_LOCK(MUTEX_VALUE)
27 }
28
29 void mutex_class::unlock()
30 {
31 FREE_UNLOCK(MUTEX_VALUE)
32 }