Advertisement
Guest User

asm lock

a guest
Aug 15th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. typedef struct {
  5. unsigned long l;
  6. unsigned long v;
  7. } apc_lock_t;
  8.  
  9. int apc_lock_init(apc_lock_t* lock)
  10. {
  11. lock->l = 0;
  12. lock->v = 0;
  13. }
  14.  
  15. int apc_lock_try(apc_lock_t* lock)
  16. {
  17. int failed = 1;
  18.  
  19. asm volatile (
  20. "xchgl %0, 0(%1)" : "=r" (failed) : "r" (&lock->l),
  21. "0" (failed)
  22. );
  23.  
  24. return failed;
  25. }
  26.  
  27. int apc_lock_get(apc_lock_t* lock)
  28. {
  29. int failed = 1;
  30.  
  31. do {
  32. failed = apc_lock_try(lock);
  33. } while (failed);
  34.  
  35. return failed;
  36. }
  37.  
  38. int apc_lock_release(apc_lock_t* lock)
  39. {
  40. int released = 0;
  41.  
  42. if (lock->l) {
  43. asm volatile (
  44. "xchgl %0, 0(%1)" : "=r" (released) : "r" (&lock->l),
  45. "0" (released)
  46. );
  47. }
  48.  
  49. return !released;
  50. }
  51.  
  52. void* pthread_test(void *input) {
  53. apc_lock_t* lock = (apc_lock_t*) input;
  54.  
  55. if (lock) {
  56. int runs = 0;
  57.  
  58. while (runs++ < 10) {
  59. printf("%lu (%d) get lock: %d\n", pthread_self(), runs, apc_lock_get(lock));
  60. usleep(1000);
  61. printf("%lu (%d) release lock: %d\n", pthread_self(), runs, apc_lock_release(lock));
  62. }
  63. }
  64.  
  65. pthread_exit(NULL);
  66. }
  67.  
  68. int main(char **argv) {
  69. apc_lock_t lock;
  70.  
  71. apc_lock_init(&lock);
  72.  
  73. pthread_t threads[8];
  74. int next = 0;
  75.  
  76. while (next < 8) {
  77. pthread_create(
  78. &threads[next], NULL,
  79. pthread_test, (void*) &lock
  80. );
  81. next++;
  82. }
  83.  
  84. while (next--) {
  85. pthread_join(
  86. threads[next], NULL);
  87. }
  88.  
  89. return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement