Preface
As a means of concurrent synchronization, spin locks are especially suitable for scenarios with less competition and short lock time. They are often used in driver and kernel code, this article describes a spin lock suitable for user-state programs. It supports WIN32 + VC and Linux + GCC (> = 4.1.2) platforms and provides C language interfaces and implementations. For details, see the following.
Interface
1 # ifdef _ cplusplus
2 extern "C "{
3 # endif
4
5 typedef struct
6 {
7 volatile long flag _;
8 volatile long * spin _;
9
10} spin_lock_t;
11
12 void spin_init (spin_lock_t * lock, long * flag );
13
14 void spin_lock (spin_lock_t * lock );
15
16int spin_trylock (spin_lock_t * lock );
17
18 void spin_unlock (spin_lock_t * lock );
19
20int spin_is_lock (spin_lock_t * lock );
21
22 # ifdef _ cplusplus
23}
24 # endif
Achieve www.2cto.com year December who master Spring and Autumn
1 # ifdef _ MSC_VER
2 # include <windows. h>
3 # elif defined (_ GNUC __)
4 # if _ GNUC __< 4 | (_ GNUC __= = 4 & _ GNUC_MINOR __< 1)
5 # error GCC version must be greater or equal than 4.1.2
6 # endif
7 # include <sched. h>
8 # else
9 # error Currently only windows and linux OS are supported
10 # endif
11
12 void spin_init (spin_lock_t * lock, long * flag)
13 {
14 # ifdef _ MSC_VER
15 InterlockedExchange (volatile long *) & lock-> flag _, 0 );
16 InterlockedExchange (volatile long *) & lock-> spin _, flag? (Long) flag :( long) & lock-> flag _);
17 # elif defined (_ GNUC __)
18 _ sync_and_and_fetch (long *) & lock-> flag _, 0 );
19 _ sync_lock_test_and_set (long *) & lock-> spin _, flag? (Long) flag :( long) & lock-> flag _);
20 # endif
21}
22
23 void spin_lock (spin_lock_t * lock)
24 {
25 # ifdef _ MSC_VER
26 for (; 0! = InterlockedExchange (volatile long *) lock-> spin _, 1 );)
27 {
28 Sleep (1 );
29}
30 # elif defined (_ GNUC __)
31 for (; 0! ==Sync_fetch_and_or (lock-> spin _, 1 );)
32 {
33 sched_yield ();
34}
35 # endif
36}
37
38int spin_trylock (spin_lock_t * lock)
39 {
40 # ifdef _ MSC_VER
41 return! InterlockedExchange (volatile long *) lock-> spin _, 1 );
42 # elif defined (_ GNUC __)
43 return! _ Sync_fetch_and_or (lock-> spin _, 1 );
44 # endif
45}
46
47 void spin_unlock (spin_lock_t * lock)
48 {
49 # ifdef _ MSC_VER
50 InterlockedExchange (volatile long *) lock-> spin _, 0 );
51 # elif defined (_ GNUC __)
52 _ sync_and_and_fetch (lock-> spin _, 0 );
53 # endif
54}
55
56int spin_is_lock (spin_lock_t * lock)
57 {
58 # ifdef _ MSC_VER
59 return InterlockedExchangeAdd (volatile long *) lock-> spin _, 0 );
60 # elif defined (_ GNUC __)
61 return _ sync_add_and_fetch (lock-> spin _, 0 );
62 # endif
63}