Guest User

Untitled

a guest
Jun 3rd, 2016
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <stdint.h>
  4. #include <unistd.h>
  5.  
  6. #include <pthread.h>
  7. #include <sys/eventfd.h>
  8.  
  9. #define SIZE 20
  10.  
  11. pthread_t threads[SIZE];
  12.  
  13. int fd; /* event file descriptor */
  14. int counter = 0;
  15.  
  16. void lock(int fd)
  17. {
  18.     int64_t value;
  19.     int ret = read(fd, &value, sizeof(int64_t));
  20.     if(ret == -1) printf("ERROR: read\n");
  21. }
  22.  
  23. void unlock(int fd)
  24. {
  25.     int64_t value = 1;
  26.     int ret = write(fd, &value, sizeof(int64_t));
  27.     if(ret == -1) printf("ERROR: write\n");
  28. }
  29.  
  30. void* execute(void* arg)
  31. {
  32.     for(int i = 0; i < 1000; i++)
  33.     {
  34.         lock(fd);
  35.         counter += 1;
  36.         unlock(fd);
  37.     }
  38. }
  39.  
  40. void init_threads()
  41. {
  42.     for(int i = 0; i < SIZE; i++)
  43.         pthread_create(&threads[i], NULL, execute, NULL);
  44. }
  45.  
  46. void destroy_threads()
  47. {
  48.     for(int i = 0; i < SIZE; i++)
  49.         pthread_join(threads[i], NULL);
  50. }
  51.  
  52. int main(void)
  53. {
  54.     /* create event file descriptor with initval=1 and options=0 */
  55.     fd = eventfd(1, 0);
  56.    
  57.     init_threads();
  58.     destroy_threads();
  59.  
  60.     printf("Counter: %d\n", counter);
  61.    
  62.     return 0;
  63. }
Add Comment
Please, Sign In to add comment