EternalHaru

Untitled

May 28th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1.  
  2. #include <sys/stat.h>
  3. #include <sys/types.h>
  4. #include <fcntl.h>
  5. #include <pthread.h>
  6. #include <stdio.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <mqueue.h>
  11.  
  12. using namespace std;
  13.  
  14.  
  15. typedef struct Arguments {
  16.     bool* flag;
  17.     timespec* tm;
  18.     mqd_t* mqid;
  19. } arguments;
  20.  
  21.  
  22. void *thread(void *args) {
  23.     puts("read thread started");
  24.     arguments *argument = (arguments*) args;
  25.     (*(argument->tm)).tv_sec = 0;
  26.     (*(argument->tm)).tv_nsec = 100000000;
  27.     char buf[100];
  28.     while (*(argument->flag)) {
  29.         while ((mq_receive(*(argument->mqid), buf, 100, 0)) <= 0) {
  30.             if (!*(argument->flag))
  31.                 return 0;
  32.             nanosleep(argument->tm, NULL);
  33.         }      
  34.         printf("Readed: %s\n", buf);
  35.         fflush(stdout);
  36.         sleep(1);
  37.     }
  38.     printf("read thread finished");
  39.     fflush(stdout);
  40.     pthread_exit(NULL);
  41. }
  42.  
  43. int main() {
  44.     char mq_name[] = "/message_queue";
  45.     bool flag = true;
  46.     pthread_t threadInit;
  47.     arguments args;
  48.     mq_attr attr;
  49.     timespec tm;
  50.     mqd_t mqid;
  51.    
  52.    
  53.     tm.tv_sec = 0;
  54.     tm.tv_nsec = 100000000;
  55.     attr = {O_NONBLOCK, 10, 64, 0};
  56.     mqid = mq_open(mq_name, O_CREAT | O_RDONLY | O_NONBLOCK, 0777, &attr);  
  57.    
  58.     args.flag = &flag;
  59.     args.tm = &tm;
  60.     args.mqid = &mqid;
  61.    
  62.     if(pthread_create(&threadInit, NULL, &thread,(void*) &args))
  63.         return EXIT_FAILURE;
  64.    
  65.     getchar();
  66.    
  67.     flag = false;
  68.    
  69.     pthread_join(threadInit, NULL);  
  70.    
  71.     mq_close(mqid);
  72.     mq_unlink(mq_name);
  73.     return EXIT_SUCCESS;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment