forked from buaazp/zimg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzspinlock.c
96 lines (82 loc) · 2.12 KB
/
zspinlock.c
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
* zimg - high performance image storage and processing system.
* http://zimg.buaa.us
*
* Copyright (c) 2013, Peter Zhao <[email protected]>.
* All rights reserved.
*
* Use and distribution licensed under the BSD license.
* See the LICENSE file for full text.
*
*/
/**
* @file zspinlock.c
* @brief Spinlock functions used for log.
* @author 招牌疯子 [email protected]
* @version 1.0
* @date 2013-07-19
*/
#include "zspinlock.h"
#ifdef _MSC_VER
#include <windows.h>
#elif defined(__GNUC__)
#if __GNUC__<4 || (__GNUC__==4 && __GNUC_MINOR__<1)
#error GCC version must be greater or equal than 4.1.2
#endif
#include <sched.h>
#else
#error Currently only windows and linux os are supported
#endif
void spin_init(spin_lock_t* lock,long* flag);
void spin_lock(spin_lock_t* lock);
int spin_trylock(spin_lock_t* lock);
void spin_unlock(spin_lock_t* lock);
int spin_is_lock(spin_lock_t* lock);
void spin_init(spin_lock_t* lock,long* flag)
{
#ifdef _MSC_VER
InterlockedExchange((volatile long*)&lock->spin_,0);
//InterlockedExchange((long*)&lock->spin_,flag?(long)flag:(long)&lock->flag_);
#elif defined(__GNUC__)
__sync_and_and_fetch((long*)&lock->spin_,0);
//__sync_lock_test_and_set((long*)&lock->spin_,flag?(long)flag:(long)&lock->flag_);
#endif
}
void spin_lock(spin_lock_t* lock)
{
#ifdef _MSC_VER
for (;0!=InterlockedExchange((volatile long*)&lock->spin_,1);)
{
;
}
#elif defined(__GNUC__)
for (;0!=__sync_fetch_and_or((long*)&lock->spin_,1);)
{
;
}
#endif
}
int spin_trylock(spin_lock_t* lock)
{
#ifdef _MSC_VER
return !InterlockedExchange((volatile long*)&lock->spin_,1);
#elif defined(__GNUC__)
return !__sync_fetch_and_or((long*)&lock->spin_,1);
#endif
}
void spin_unlock(spin_lock_t* lock)
{
#ifdef _MSC_VER
InterlockedExchange((volatile long*)&lock->spin_,0);
#elif defined(__GNUC__)
__sync_and_and_fetch((long*)&lock->spin_,0);
#endif
}
int spin_is_lock(spin_lock_t* lock)
{
#ifdef _MSC_VER
return InterlockedExchangeAdd((volatile long*)&lock->spin_,0);
#elif defined(__GNUC__)
return __sync_add_and_fetch((long*)&lock->spin_,0);
#endif
}