Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "pch.h"
- #include <iostream>
- #include <mutex>
- #include <vector>
- #include <chrono>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- // some global variables
- condition_variable waitCondition;
- mutex mutexVar;
- bool isWaiting = true;
- bool notFinished = true;
- // each thread prints its number
- void threadFunction(int num) {
- unique_lock<mutex> lock(mutexVar);
- while (notFinished) {
- waitCondition.wait(lock, [&] { return !isWaiting; });
- if (notFinished) {
- isWaiting = true;
- cout << num << "\n";
- }
- }
- }
- int inputAmountOfThreads() {
- int n;
- cin >> n;
- if (n <= 3) {
- return inputAmountOfThreads();
- }
- else {
- return n;
- }
- }
- void initializeThreads(int n, vector<thread>& threads) {
- for (int i = 1; i <= n; i++) {
- threads[i] = thread(threadFunction, i);
- }
- }
- void wakeUpThreads(int n, vector<thread>& threads) {
- int amountOfDoneCalls = 0;
- int amountOfRequestedCalls = 10;
- chrono::high_resolution_clock::time_point lastTimePoint = chrono::high_resolution_clock::now();
- while (amountOfDoneCalls < amountOfRequestedCalls) {
- if (chrono::duration_cast<chrono::seconds>
- (chrono::high_resolution_clock::now() - lastTimePoint).count() > 0.0001) {
- isWaiting = false;
- waitCondition.notify_one();
- lastTimePoint = chrono::high_resolution_clock::now();
- amountOfDoneCalls++;
- }
- }
- }
- void detachThreads(int n, vector<thread>& threads) {
- waitCondition.notify_all();
- for (int i = 1; i <= n; i++) {
- threads[i].join();
- }
- }
- int main()
- {
- /*freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);*/
- srand(time(NULL));
- int n;
- n = inputAmountOfThreads();
- vector <thread> threads(n + 1);
- initializeThreads(n, threads);
- wakeUpThreads(n, threads);
- notFinished = false;
- detachThreads(n, threads);
- return 0;
- }
Add Comment
Please, Sign In to add comment