Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <cstring>
  6. #include <fcntl.h>
  7. #include <fstream>
  8. #include <sys/types.h>
  9. #include <sys/ipc.h>
  10. #include <sys/sem.h>
  11. #include <semaphore.h>
  12. struct Args {
  13.     int flag;
  14.     char * fileName = "/home/dimka/text.txt";
  15.     std::fstream myfile;
  16.     sem_t *mutex;
  17.  
  18. };
  19. void* func_1(void* args){
  20.     Args *arg=(Args*) args;
  21.     char input ='2';
  22.     std::cout<<"Enter in critical sector"<<std::endl;
  23.     while(arg->flag==0){
  24.         //sem_wait(arg->mutex);
  25.         for (int i = 0; i < 5; ++i) {
  26.             std::cout<<"Write in file:"<<input<<std::endl;
  27.             arg->myfile << input<<std::flush;
  28.             sleep(1);
  29.         }
  30.         std::cout<<"Exit from critical sector"<<std::endl;
  31.         //sem_post(arg->mutex);
  32.         sleep(1);
  33.     }
  34. }
  35. int main() {
  36.     Args file;
  37.     file.flag =0;
  38.     /*if ((file.mutex = sem_open("mysemaphor", O_CREAT, 0644, 1)) == SEM_FAILED) {
  39.         perror("semaphore initilization");
  40.         exit(1);
  41.     }*/
  42.     file.myfile.open(file.fileName,std::fstream::app);
  43.     pthread_t pthread_2;
  44.     pthread_create(&pthread_2, NULL, func_1, (void*) &file);
  45.     getchar();
  46.     file.flag=1;
  47.     pthread_join(pthread_2, nullptr);
  48.     file.myfile.close();
  49.     sem_close(file.mutex);
  50.     sem_unlink("mysemaphore");
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement