我必須在C++中編寫多生產者 - 消費者系統,但是我試圖將模型的每個部分(具有正確緩衝區的線程)放在一起。模型的基本功能是:我有一個執行函數的初始線程。返回的結果需要放入未確定數量的緩衝區中,因爲函數處理的每個元素都不相同,並且需要在單個線程中處理。然後,通過存儲在緩衝區中的數據,另一個線程需要獲取這些緩衝區的數據以執行另一個功能,並且需要將這個返回再次放入一些緩衝區。C++中的無鎖多生產者多個消費者
在我有創造了這個緩衝結構的那一刻:
template <typename T>
class buffer {
public:
atomic_buffer(int n);
int bufSize() const noexcept;
bool bufEmpty() const noexcept;
bool full() const noexcept;
~atomic_buffer() = default;
void put(const T & x, bool last) noexcept;
std::pair<bool,T> get() noexcept;
private:
int next_pos(int p) const noexcept;
private:
struct item {
bool last;
T value;
};
const int size_;
std::unique_ptr<item[]> buf_;
alignas(64) std::atomic<int> nextRd_ {0};
alignas(64) std::atomic<int> nextWrt_ {0};
};
我還創建了一個vector
結構存儲集合聯合國緩衝區,以滿足線程需要的人數不詳。
std::vector<std::unique_ptr<locked_buffer<std::pair<int, std::vector<std::vector<unsigned char>>>>>> v1;
for(int i=0; i<n; i++){
v1.push_back(std::unique_ptr<locked_buffer<std::pair<int,std::vector<std::vector<unsigned char>>>>> (new locked_buffer<std::pair<int, std::vector<std::vector<unsigned char>>>>(aux)));
}
編輯:
我不明白你的問題。您可以添加數據流的圖紙嗎? – 1000ml
@ 1000ml編輯。 – giorgioW
不知道更多的上下文,這看起來像有一個生產者線程可以創建任務。這些任務是並行執行的。所有結果都由一個線程使用。在我看來,你甚至不需要在緩衝區上進行任何同步。 – 1000ml