Advertisement
Guest User

locking without mutex/rwlocks

a guest
Aug 15th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  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. if (released) {
  50. /* got lock */
  51. printf("free'd lock...\n");
  52. }
  53.  
  54. return !released;
  55. }
  56.  
  57. void* pthread_test(void *input) {
  58. apc_lock_t* lock = (apc_lock_t*) input;
  59.  
  60. if (lock) {
  61. int runs = 0;
  62.  
  63. while (runs++ < 1000) {
  64. printf("%lu get lock: %d\n", pthread_self(), apc_lock_get(lock));
  65. sleep(1);
  66. printf("%lu release lock: %d\n", pthread_self(), apc_lock_release(lock));
  67. }
  68. }
  69. pthread_exit(NULL);
  70. }
  71.  
  72. int main(char **argv) {
  73. apc_lock_t lock;
  74.  
  75. apc_lock_init(&lock);
  76.  
  77. pthread_t threads[100];
  78. int next = 0;
  79.  
  80. while (next++ < 100) {
  81. pthread_create(
  82. &threads[next], NULL,
  83. pthread_test, (void*) &lock
  84. );
  85. }
  86.  
  87. sleep(1000);
  88.  
  89. while (next--) {
  90. pthread_join(threads[next], NULL);
  91. }
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement