Advertisement
Guest User

Untitled

a guest
Apr 9th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <termios.h>
  5. #include <fcntl.h>
  6. #include <sys/stat.h>
  7. #include <semaphore.h>
  8. #include <fstream>
  9.  
  10. const int name_size = 10;
  11.  
  12. const char sem_name[name_size] = "/LAB5";
  13. const char file_name[name_size] = "lab5.txt";
  14.  
  15. std::ofstream file;
  16.  
  17. struct argum
  18. {
  19.         int fl = 0;
  20.         sem_t* sem_id;
  21. };
  22.  
  23. void* _thread(void* args)
  24. {
  25.         char ch = '1';
  26.         while(static_cast<argum*>(args)->fl != 1)
  27.         {
  28.                 sem_wait(static_cast<argum*>(args)->sem_id);
  29.                 for (int i = 1; i < 5; ++i)
  30.                 {
  31.                         file << ch;
  32.                         file.flush();
  33.                         std::cout << ch;
  34.                         std::cout.flush();
  35.                         sleep(1);
  36.                 }
  37.                 sem_post(static_cast<argum*>(args)->sem_id);
  38.                 sleep(1);
  39.         }
  40.         auto code = new int;
  41.         *code = 1;
  42.         pthread_exit(code);
  43. }
  44.  
  45.  
  46.  
  47. int main(int argc, char *argv[])
  48. {
  49.         pthread_t id;
  50.         void *ret;
  51.         argum arguments;
  52.         arguments.sem_id = sem_open(sem_name, O_CREAT, 0644, 1);
  53.         std::cout << arguments.sem_id << '\n';
  54.         file.open(file_name, std::ios_base::app);
  55.         if(pthread_create(&id,NULL,_thread,&arguments))
  56.         {
  57.                 return 1;
  58.         }
  59.         else
  60.         {
  61.                 std::cout << "thread started \n";
  62.         }
  63.         std::cout << "system paused, press enter to continue\n";
  64.         getchar();
  65.         arguments.fl = 1;
  66.         pthread_join(id, &ret);
  67.         std::cout << "thread returned: " << *(int *)ret << "\n";
  68.         delete (int *)ret;
  69.         file.close();
  70.         sem_close(arguments.sem_id);
  71.         sem_unlink(sem_name);
  72.         return 0;
  73.        
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement