HomoCivicus

PL-M2-T1

Oct 8th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <mutex>
  4. #include <vector>
  5. #include <chrono>
  6. #include <cstdlib>
  7. #include <ctime>
  8. using namespace std;
  9.  
  10. // some global variables
  11.  
  12. condition_variable waitCondition;
  13. mutex mutexVar;
  14. bool isWaiting = true;
  15. bool notFinished = true;
  16.  
  17. // each thread prints its number
  18. void threadFunction(int num) {
  19.     unique_lock<mutex> lock(mutexVar);
  20.  
  21.     while (notFinished) {
  22.         waitCondition.wait(lock, [&] { return !isWaiting; });
  23.        
  24.         if (notFinished) {
  25.             isWaiting = true;
  26.             cout << num << "\n";
  27.         }
  28.     }
  29. }
  30.  
  31. int inputAmountOfThreads() {
  32.     int n;
  33.     cin >> n;
  34.  
  35.     if (n <= 3) {
  36.         return inputAmountOfThreads();
  37.     }
  38.     else {
  39.         return n;
  40.     }
  41. }
  42.  
  43. void initializeThreads(int n, vector<thread>& threads) {
  44.     for (int i = 1; i <= n; i++) {
  45.         threads[i] = thread(threadFunction, i);
  46.     }
  47. }
  48.  
  49. void wakeUpThreads(int n, vector<thread>& threads) {
  50.     int amountOfDoneCalls = 0;
  51.     int amountOfRequestedCalls = 10;
  52.     chrono::high_resolution_clock::time_point lastTimePoint = chrono::high_resolution_clock::now();
  53.  
  54.     while (amountOfDoneCalls < amountOfRequestedCalls) {
  55.         if (chrono::duration_cast<chrono::seconds>
  56.             (chrono::high_resolution_clock::now() - lastTimePoint).count() > 0.0001) {
  57.  
  58.             isWaiting = false;
  59.             waitCondition.notify_one();
  60.  
  61.             lastTimePoint = chrono::high_resolution_clock::now();
  62.             amountOfDoneCalls++;
  63.         }
  64.     }
  65. }
  66.  
  67. void detachThreads(int n, vector<thread>& threads) {
  68.     waitCondition.notify_all();
  69.  
  70.     for (int i = 1; i <= n; i++) {
  71.         threads[i].join();
  72.     }
  73. }
  74.  
  75. int main()
  76. {
  77.     /*freopen("input.txt", "r", stdin);
  78.     freopen("output.txt", "w", stdout);*/
  79.     srand(time(NULL));
  80.  
  81.     int n;
  82.     n = inputAmountOfThreads();
  83.     vector <thread> threads(n + 1);
  84.  
  85.     initializeThreads(n, threads);
  86.     wakeUpThreads(n, threads);
  87.  
  88.     notFinished = false;
  89.     detachThreads(n, threads);
  90.  
  91.     return 0;
  92. }
Add Comment
Please, Sign In to add comment