How can organize a below program so that it will work as follows: For each time each thread must wait as long as other threads has not reached that time. At the point when for the given time all threads are "executed" the result value should be printed out.
#include <iostream>
#include <thread>
#include <mutex>
const int numThreads = 4;
typedef double Time;
double resultForGivenTime = 0;
class Printer
{
public:
void print(Time time, double result)
{
mtx.lock();
std::cout << "Time:" << time << " -> Result:" << result << std::endl;
resultForGivenTime = 0;
mtx.unlock();
}
private:
std::mutex mtx;
};
Printer p;
void doIt (Printer& p, Time& t, int& id)
{
//Is it possible to create here a barier so that
//program output will look like this:
//Time: 0 -> Result 6
//Time: 1 -> Result 6
//Time: 2 -> Result 6
//Time: 3 -> Result 6
//Time: 4 -> Result 6
resultForGivenTime += id;
p.print(t, resultForGivenTime);
}
void handler(int id)
{
for (Time time = 0.0; time < 5.0; ++time)
{
doIt(p, time, id);
}
}
int main()
{
std::thread threads[numThreads];
for (int i = 0; i < numThreads; ++i)
threads[i] = std::thread(handler, i);
for (auto& th : threads) th.join();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire