gpt4 book ai didi

c++ - 创建阻塞队列

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:18 25 4
gpt4 key购买 nike

有时 BlockingQueue 的实现和执行会正常工作。有时它会出现段错误。知道为什么吗?

#include <thread>
using std::thread;
#include <mutex>
using std::mutex;
#include <iostream>
using std::cout;
using std::endl;
#include <queue>
using std::queue;
#include <string>
using std::string;
using std::to_string;
#include <functional>
using std::ref;

template <typename T>
class BlockingQueue {
private:
mutex mutex_;
queue<T> queue_;
public:
T pop() {
this->mutex_.lock();
T value = this->queue_.front();
this->queue_.pop();
this->mutex_.unlock();
return value;
}

void push(T value) {
this->mutex_.lock();
this->queue_.push(value);
this->mutex_.unlock();
}

bool empty() {
this->mutex_.lock();
bool check = this->queue_.empty();
this->mutex_.unlock();
return check;
}
};

void fillWorkQueue(BlockingQueue<string>& workQueue) {
int size = 40000;
for(int i = 0; i < size; i++)
workQueue.push(to_string(i));
}

void doWork(BlockingQueue<string>& workQueue) {
while(!workQueue.empty()) {
workQueue.pop();
}
}

void multiThreaded() {
BlockingQueue<string> workQueue;
fillWorkQueue(workQueue);
thread t1(doWork, ref(workQueue));
thread t2(doWork, ref(workQueue));
t1.join();
t2.join();
cout << "done\n";
}

int main() {
cout << endl;

// Multi Threaded
cout << "multiThreaded\n";
multiThreaded();
cout << endl;
}

最佳答案

看这里:

What do I get from front() of empty std container?

如果你在空容器上调用 .front() 会发生不好的事情,最好先检查 .empty()

尝试:

T pop() {
this->mutex_.lock();
T value;
if( !this->queue_.empty() )
{
value = this->queue_.front(); // undefined behavior if queue_ is empty
// may segfault, may throw, etc.
this->queue_.pop();
}
this->mutex_.unlock();
return value;
}

注意:由于原子操作对这种队列很重要,我建议更改 API:

bool pop(T &t);  // returns false if there was nothing to read.

更好的是,如果您实际在重要的地方使用它,您可能希望在删除之前标记正在使用的项目以防失败。

bool peekAndMark(T &t);  // allows one "marked" item per thread
void deleteMarked(); // if an item is marked correctly, pops it.
void unmark(); // abandons the mark. (rollback)

关于c++ - 创建阻塞队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23661759/

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