Advertisement
Guest User

again

a guest
Aug 15th, 2013
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. typedef struct {
  5. unsigned long state;
  6. } apc_lock_t;
  7.  
  8. int apc_lock_init(apc_lock_t* lock)
  9. {
  10. lock->state = 0;
  11. }
  12.  
  13. int apc_lock_try(apc_lock_t* lock)
  14. {
  15. int failed = 1;
  16.  
  17. asm volatile
  18. (
  19. "xchgl %0, 0(%1)" :
  20. "=r" (failed) : "r" (&lock->state),
  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(
  33. lock);
  34. usleep(0);
  35. } while (failed);
  36.  
  37. return failed;
  38. }
  39.  
  40. int apc_lock_release(apc_lock_t* lock)
  41. {
  42. int released = 0;
  43.  
  44. asm volatile (
  45. "xchg %0, 0(%1)" : "=r" (released) : "r" (&lock->state),
  46. "0" (released)
  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. printf("%lu has lock ...\n", pthread_self());
  61. sleep(1);
  62. printf("%lu (%d) release lock: %d\n", pthread_self(), runs, apc_lock_release(lock));
  63. fflush(stdout);
  64. }
  65. }
  66.  
  67. pthread_exit(NULL);
  68. }
  69.  
  70. int main(char **argv) {
  71. apc_lock_t lock;
  72.  
  73. apc_lock_init(&lock);
  74.  
  75. pthread_t threads[8];
  76. int next = 0;
  77.  
  78. while (next < 8) {
  79. pthread_create(
  80. &threads[next], NULL,
  81. pthread_test, (void*) &lock
  82. );
  83. next++;
  84. }
  85.  
  86. while (next--) {
  87. pthread_join(
  88. threads[next], NULL);
  89. }
  90.  
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement