线程安全的 std::queue 类 c++17

问题描述 投票:0回答:2

queue_safe.cpp

#pragma once

#include <iostream>
#include <queue>
#include <string>
#include <mutex>
#include <condition_variable>
#include <chrono>

#include "queue_safe.h"

void SafeQueue::initialize() {

    /* initialize a std::queue */

    safe_queue = {};
    
}

std::string SafeQueue::get() {

    std::unique_lock<std::mutex> condition_lock(queue_lock);

    /* wait 20 seconds */

    std::chrono::system_clock::time_point wait = std::chrono::system_clock::now() + std::chrono::system_clock::duration(20);

    while (safe_queue.empty()) {

        if (ready.wait_until(condition_lock, wait) == std::cv_status::timeout) {

            /* timeout was reached, no items left */

            std::cout << "no items left in queue..." << std::endl;
        }

        std::string element = safe_queue.front();

        safe_queue.pop();

        return element;
    }

    /* not empty, return an element */
    
    std::string element = safe_queue.front();

    safe_queue.pop();

    return element;

}

void SafeQueue::put(std::string& element) {

    /* does not need to be thread-safe */

    safe_queue.push(element);

}

uint8_t SafeQueue::empty() {

    std::unique_lock<std::mutex> condition_lock(queue_lock);
    
    if (safe_queue.size() == 0) {
        return 1;
    }

    return 0;

}

queue_safe.h

#pragma once

#include <string>
#include <mutex>
#include <queue>
#include <condition_variable>

class SafeQueue {
public:
    std::condition_variable ready;
    std::mutex queue_lock;

    std::queue<std::string> safe_queue;
    uint8_t empty();
    void initialize();
    void put(std::string& element);
    std::string get();
};

这显示了我的代码,用于安全地从队列中获取字符串。我想等待最多 20 秒才能使元素变得可用,因此我使用条件变量、唯一锁,最后

wait_until
。据我所知,我不需要在推送(添加)函数周围使用互斥体。 目标:创建一个线程安全队列,该队列在指定时间段(此处为 20 秒)后超时。
问题:这真的是线程安全的吗?我是否需要围绕推送功能设置互斥体/防护装置,如果需要,为什么?
好的,所以 1) 出于可读性的目的,我需要使用 bool 而不是无符号整数,2) 我需要同步推送和弹出,3) 时间点不是真正的 20 秒。 4)我需要处理“虚假唤醒”

c++ queue thread-safety c++17
2个回答
1
投票

据我所知,我不需要在推送(添加)函数周围使用互斥体。

你知道错了。

这真的是线程安全的吗?

没有。

我需要围绕推送功能设置互斥体/防护吗

是的。

为什么?

因为对容器的无序修改会导致未定义的行为。

std::queue::push
修改容器。


-5
投票

@eerorika 小F是谁啊??? 把态度留在你妈家里???好吧????

© www.soinside.com 2019 - 2024. All rights reserved.