Guest User

Untitled

a guest
Jun 18th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. static volatile int flag0 __attribute__((aligned(64)));
  6. static volatile int flag1 __attribute__((aligned(64)));
  7. static volatile int turn __attribute__((aligned(64)));
  8.  
  9. static void
  10. lock(volatile int *my_flag, volatile int *other_flag, int other_id)
  11. {
  12. *my_flag = 1;
  13. turn = other_id;
  14. while (*other_flag && turn == other_id) {
  15. }
  16. asm volatile ("" : : : "memory");
  17. }
  18.  
  19. static void
  20. unlock(volatile int *my_flag)
  21. {
  22. asm volatile ("" : : : "memory");
  23. *my_flag = 0;
  24. }
  25.  
  26. #define LOOP_COUNT 100000000
  27. static int counter = 0;
  28.  
  29. static void*
  30. task0(void *arg)
  31. {
  32. int i;
  33. for (i = LOOP_COUNT; i != 0; i--) {
  34. lock(&flag0, &flag1, 1);
  35. counter++;
  36. unlock(&flag0);
  37. }
  38. return NULL;
  39. }
  40.  
  41. static void*
  42. task1(void *arg)
  43. {
  44. int i;
  45. for (i = LOOP_COUNT; i != 0; i--) {
  46. lock(&flag1, &flag0, 0);
  47. counter++;
  48. unlock(&flag1);
  49. }
  50. return NULL;
  51. }
  52.  
  53. int
  54. main(int argc, char *argv[])
  55. {
  56. flag0 = 0;
  57. flag1 = 0;
  58.  
  59. pthread_t t0, t1;
  60. if (pthread_create(&t0, NULL, task0, NULL) ||
  61. pthread_create(&t1, NULL, task1, NULL)) {
  62. fprintf(stderr, "pthread_create\n");
  63. exit(1);
  64. }
  65.  
  66. if (pthread_join(t0, NULL) ||
  67. pthread_join(t1, NULL)) {
  68. fprintf(stderr, "pthread_join\n");
  69. exit(1);
  70. }
  71.  
  72. printf("counter = %d\n", counter);
  73. printf("difference = %d\n", LOOP_COUNT * 2 - counter);
  74. return 0;
  75. }
Add Comment
Please, Sign In to add comment