c++ - 为每次 c++ 创建一个障碍

标签 c++ multithreading c++11 thread-safety

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

#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/

相关文章:

c++ - 传递模板数组时 sizeof 是如何工作的?

c++ - 如何反序列化数组?

java - 控制台上的光标似乎很滞后

java - 如果多个线程调用CountDownLatch的await()方法会发生什么?

mysql - fork 还是不 fork ?

c++ - 按完整路径打开文件

c++ - 当我尝试函数重载时数组获得垃圾值

c++ - 如何将带有 vector 或其他标准库容器的对象保存到 C++ 中的二进制文件?

c++ - 我可以将 final 关键字应用于 C++11 中的 POD(标准布局)结构吗?我是不是该?

c++ - 在 C++03 中是否可以使用非 const 右值引用?