Created
December 17, 2011 13:52
-
-
Save matteobertozzi/1490264 to your computer and use it in GitHub Desktop.
Ticket Lock (__sync_fetch_and_add)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define spinlock_t union ticket_lock | |
| #define spin_init ticket_init | |
| #define spin_destroy ticket_destroy | |
| #define spin_lock ticket_acquire | |
| #define spin_unlock ticket_release | |
| union ticket_lock { | |
| volatile unsigned int data; | |
| struct { | |
| volatile unsigned short next_ticket; | |
| volatile unsigned short now_serving; | |
| } s; | |
| }; | |
| void ticket_init (union ticket_lock *lock) { | |
| lock->s.now_serving = 0; | |
| lock->s.next_ticket = 0; | |
| } | |
| void ticket_destroy (union ticket_lock *lock) { | |
| lock->s.now_serving = 0; | |
| lock->s.next_ticket = 0; | |
| } | |
| int ticket_acquire (union ticket_lock *lock) { | |
| unsigned int my_ticket; | |
| int spin = 0; | |
| my_ticket = __sync_fetch_and_add(&(lock->s.next_ticket), 1); | |
| while (lock->s.now_serving != my_ticket) | |
| spin++; | |
| return(spin); | |
| } | |
| void ticket_release (union ticket_lock *lock) { | |
| lock->s.now_serving += 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment