如何组织下面的程序,使其能够按以下方式工作:
对于每个时间,每个线程必须等待,直到所有其他线程都没有达到该时间。在给定时间内所有线程都被“执行”时,应将结果值打印出来。

#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             # one or four time
    //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;
}

最佳答案

您可以结合使用条件变量和计数器。您可以在此处找到一个很好的用法示例:

http://www.cplusplus.com/reference/condition_variable/condition_variable/

另外,如果您有Boost库可用,则可以使用barrier类,该类提供了一个不错的包装器:

#include <boost/thread/barrier.hpp>

class barrier
{
public:
    barrier(barrier const&) = delete;
    barrier& operator=(barrier const&) = delete;

    barrier(unsigned int count);
    template <typename F>
    barrier(unsigned int count, F&&);

    ~barrier();

    bool wait();
    void count_down_and_wait();
};

关于c++ - 每次C++都会创建障碍,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28916238/

10-17 00:23