gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:47 24 4
gpt4 key购买 nike

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com