我的程序中有4个线程。我想一次执行所有它们,一旦全部执行完,那么我只想输入下一个执行迭代。
我在堆栈溢出中获得了一个代码,该代码在C++中实现了boost::barrier
函数。但这似乎对我不起作用。对于一次迭代,它工作正常。但是对于下一次迭代,程序执行只是挂起。
//这是我的最高代码:
#include <iostream>
#include <stdio.h>
#include <thread>
#include "abc_func.hpp"
#include <vector>
using namespace std;
int main() {
abc obj1;
obj1.num_threads(4);
std::thread t1([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_write(1));
};
});
std::thread t2([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_read(2));
};
});
std::thread t3([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_write(3));
};
});
std::thread t4([&obj1](){
for (int i=0; i<5; i++) {
while (!obj1.abc_read(4));
};
});
t1.join();
t2.join();
t3.join();
t4.join();
// cout << "done: " << obj1.done << endl;
// cout << "done: " << obj2.done << endl;
// cout << "wr_count: " << obj1.wr_count << endl;
return 0;
}
//这是abc_func.hpp
#include <iostream>
#include <stdio.h>
#include <thread>
#include <barrier.hpp>
using namespace std;
class abc {
size_t n_threads;
public:
abc() : n_threads(0) {};
void num_threads (size_t l) {
n_threads = l;
}
Barrier task_bar{n_threads};
bool abc_write (auto id) {
thread_local int wr_count = 0;
if (wr_count == 1) {
std::cout << "write thread waiting" << id << endl;
task_bar.Wait();
wr_count = 0;
};
std::cout << "write thread running " << id << endl;
++wr_count;
return true;
}
bool abc_read (auto id) {
thread_local int rd_count=0;
if (rd_count == 1) {
std::cout << "read thread waiting" << id << endl;
task_bar.Wait();
rd_count = 0;
};
std::cout << "read thread running " << id << endl;
++rd_count;
return true;
}
};
//和我在栈上溢出的屏障类代码
#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <stdio.h>
class Barrier {
public:
explicit Barrier(std::size_t iCount) :
mThreshold(iCount),
mCount(iCount),
mGeneration(0) {
}
void Wait() {
std::unique_lock<std::mutex> lLock{mMutex};
auto lGen = mGeneration;
if (!--mCount) {
mGeneration++;
mCount = mThreshold;
mCond.notify_all();
} else {
mCond.wait(lLock, [this, lGen] { return lGen != mGeneration; });
}
}
private:
std::mutex mMutex;
std::condition_variable mCond;
std::size_t mThreshold;
std::size_t mCount;
std::size_t mGeneration;
};
最佳答案
此代码的问题是成员
Barrier task_bar{n_threads};
当
n_threads
为0时,它在开始时初始化一次。稍后,当您调用obj1.num_threads(4);
屏障对象未更新。
当您更新障碍时,它也会按预期工作
class Barrier {
public:
// ...
void num_threads(size_t n) {
mThreshold = n;
mCount = n;
}
// ...
};
和
abc::num_threads()
void num_threads (size_t l) {
n_threads = l;
task_bar.num_threads(l);
}
关于c++ - 如何在C++中创建屏障?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48712881/