Advertisement
teknoraver

c switch

Dec 19th, 2019
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <time.h>
  4. #include <fcntl.h>
  5. #include <pthread.h>
  6.  
  7. struct iter {
  8.     int in, out;
  9. };
  10.  
  11. static long counter;
  12.  
  13. static void * inc(void *arg)
  14. {
  15.     struct iter *iter = (struct iter *)arg;
  16.     int buf;
  17.  
  18.     while (read(iter->in, &buf, sizeof(buf)) > 0) {
  19.         buf++;
  20.         counter = buf;
  21.         write(iter->out, &buf, sizeof(buf));
  22.     }
  23.  
  24.     close(iter->in);
  25.     close(iter->out);
  26.     return NULL;
  27. }
  28.  
  29. int main(int argc, char *argv[])
  30. {
  31.     pthread_t t1, t2;
  32.     int fds[4];
  33.  
  34.     pipe(fds);
  35.     pipe(fds+2);
  36.  
  37.     struct iter iter1 = {
  38.         .in = fds[0],
  39.         .out = fds[3],
  40.     };
  41.     struct iter iter2 = {
  42.         .in = fds[2],
  43.         .out = fds[1],
  44.     };
  45.  
  46.     pthread_create(&t1, NULL, inc, &iter1);
  47.     pthread_create(&t2, NULL, inc, &iter2);
  48.  
  49.     write(iter1.out, &counter, sizeof(counter));
  50.     sleep(1);
  51.     pthread_cancel(t1);
  52.     pthread_cancel(t2);
  53.  
  54.     printf("messages/sec: %lu\n", counter);
  55.     printf("time for message: %luns\n", 1000000000 / counter);
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement