Advertisement
EternalHaru

Untitled

May 28th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. #include <sys/mman.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <semaphore.h>
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <stdlib.h>
  8. #include <time.h>
  9. #include <pthread.h>
  10. #include <errno.h>
  11.  
  12.  
  13. typedef struct Arguments {
  14.     bool* flag;
  15.     timespec* tm;
  16.     sem_t* semForWrite;
  17.     sem_t* semForRead;
  18.     unsigned int* localVar;
  19. } arguments;
  20.  
  21.  
  22.  
  23. void *thread(void *args){
  24.     puts("read thread started");
  25.     arguments *argument = (arguments*) args;
  26.     (*(argument->tm)).tv_sec = 0;
  27.     (*(argument->tm)).tv_nsec = 100000000;
  28.     while (*(argument->flag)){
  29.         while (sem_trywait(argument->semForWrite) != 0) {
  30.             nanosleep(argument->tm, NULL);
  31.             if (!*(argument->flag))
  32.                 return 0;
  33.         }
  34.         printf("Readed: %u\n", *(argument->localVar));
  35.         sem_post(argument->semForRead);
  36.         sleep(1);
  37.     }
  38.     pthread_exit(NULL);
  39. }
  40.  
  41. int main(){
  42.     arguments args;
  43.     sem_t *semForWrite;
  44.     sem_t *semForRead;
  45.     unsigned int *localVar;
  46.     char SemForReadName[] = "some_random_name_read_7";
  47.     char SemForWriteName[] = "some_random_name_write_7";
  48.     char SharedMemoryName[] = "some_random_mem_name_7";
  49.     bool flag = true;
  50.     pthread_t threadInit;
  51.     timespec tm;
  52.  
  53.     int fd = shm_open(SharedMemoryName, O_CREAT | O_RDWR, 0777);
  54.     ftruncate(fd, sizeof(unsigned int));
  55.     localVar = (unsigned int*)mmap(0, sizeof(unsigned int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  56.    
  57.     semForWrite = sem_open(SemForWriteName, O_CREAT, 0644, 0);
  58.     semForRead = sem_open(SemForReadName, O_CREAT, 0644, 0);
  59.  
  60.     args.tm = &tm;
  61.     args.flag = &flag;
  62.     args.localVar = localVar;
  63.     args.semForRead = semForRead;
  64.     args.semForWrite = semForWrite;
  65.    
  66.     if(pthread_create(&threadInit, NULL, &thread, (void*)&args)){
  67.         return EXIT_FAILURE;
  68.     }
  69.    
  70.     getchar();
  71.    
  72.     flag = false;
  73.    
  74.     pthread_join(threadInit, NULL);
  75.    
  76.     sem_close(semForRead);
  77.     sem_unlink(SemForReadName);
  78.     sem_close(semForWrite);
  79.     sem_unlink(SemForWriteName);
  80.    
  81.     munmap(&localVar, 4);
  82.     close(fd);
  83.     shm_unlink(SharedMemoryName);
  84.    
  85.     return EXIT_SUCCESS;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement