Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 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. //структура для флага,названия файла,потока для работы с файлом и именованного семафора
  13. struct Args {
  14.     int flag;
  15.     char * fileName = "/home/dimka/text.txt";
  16.     std::fstream myfile;
  17.     sem_t *mutex;
  18.  
  19. };
  20. void* func_1(void* args){
  21.     Args *arg=(Args*) args;
  22.     char input ='2';
  23.     std::cout<<"Enter in critical sector"<<std::endl;
  24.     while(arg->flag==0){
  25.         //блокируем семафор
  26.         sem_wait(arg->mutex);
  27.         for (int i = 0; i < 5; ++i) {
  28.             std::cout<<"Write in file:"<<input<<std::endl;
  29.             //записываем в файл
  30.             arg->myfile << input<<std::flush;
  31.             sleep(1);
  32.         }
  33.         std::cout<<"Exit from critical sector"<<std::endl;
  34.         //разблокируем семафор
  35.         sem_post(arg->mutex);
  36.         sleep(1);
  37.     }
  38. }
  39. int main() {
  40.     Args file;
  41.     file.flag =0;
  42.     //создаем семафор
  43.     if ((file.mutex = sem_open("mysemaphor", O_CREAT, 0644, 1)) == SEM_FAILED) {
  44.         perror("semaphore initilization");
  45.         exit(1);
  46.     }
  47.     //открываем семафор
  48.     file.myfile.open(file.fileName,std::fstream::app);
  49.     pthread_t pthread_2;
  50.     pthread_create(&pthread_2, NULL, func_1, (void*) &file);
  51.     getchar();
  52.     file.flag=1;
  53.     pthread_join(pthread_2, nullptr);
  54.     //закрываем файл
  55.     file.myfile.close();
  56.     //закрываем семафор
  57.     sem_close(file.mutex);
  58.     //удаляем семафор
  59.     sem_unlink("mysemaphore");
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement