Advertisement
EternalHaru

Untitled

May 28th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 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. typedef struct Arguments {
  13.     bool* flag;
  14.     timespec* tm;
  15.     sem_t* semForWrite;
  16.     sem_t* semForRead;
  17.     unsigned int* localVar;
  18. } arguments;
  19.  
  20.  
  21.  
  22. void *thread(void *args){
  23.     puts("write thread started");
  24.     arguments *argument = (arguments*) args;
  25.     (*(argument->tm)).tv_sec = 0;
  26.     (*(argument->tm)).tv_nsec = 100000000;
  27.     while (*(argument->flag)) {
  28.         *(argument->localVar) = rand() % 1000;
  29.         printf("Writed: %u\n", *(argument->localVar));
  30.         sem_post(argument->semForWrite);
  31.         while (sem_trywait(argument->semForRead) != 0) {
  32.             nanosleep(argument->tm, NULL);
  33.             if (!*(argument->flag))
  34.                 return 0;
  35.         }
  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.     srand(time(NULL));
  58.  
  59.     semForWrite = sem_open(SemForWriteName, O_CREAT, 0644, 0);
  60.     semForRead = sem_open(SemForReadName, O_CREAT, 0644, 0);
  61.  
  62.     args.tm = &tm;
  63.     args.flag = &flag;
  64.     args.localVar = localVar;
  65.     args.semForRead = semForRead;
  66.     args.semForWrite = semForWrite;
  67.    
  68.     if(pthread_create(&threadInit, NULL, &thread, (void*)&args)){
  69.         return EXIT_FAILURE;
  70.     }
  71.    
  72.     getchar();
  73.    
  74.     flag = false;
  75.    
  76.     pthread_join(threadInit, NULL);
  77.    
  78.     sem_close(semForRead);
  79.     sem_unlink(SemForReadName);
  80.     sem_close(semForWrite);
  81.     sem_unlink(SemForWriteName);
  82.    
  83.     munmap(&localVar, 4);
  84.     close(fd);
  85.     shm_unlink(SharedMemoryName);
  86.    
  87.     return EXIT_SUCCESS;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement