gpt4 book ai didi

c++ - 如果存在仅推送线程和仅弹出线程,C++ std::queue 是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:34 37 4
gpt4 key购买 nike

我想知道这种情况是否(线程)安全。

有一个线程只推送到一个std::queue。
还有另一个线程只从 std::queue 弹出。
由于队列是否为空,线程安全地管理,后面的线程不会弹出失败。

你能帮帮我吗?

谢谢。

最佳答案

我认为答案是否定的。

标准说 (§23.2.2/1):

For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].

至少在我解释事物(和 Herb Sutter seems to agree )时,这意味着那些函数(并且那些函数)可以被视为“线程安全”。 Push 和 pop 不在列表中,因此您不能假设它们是线程安全的。

我还要补充一点,即使弹出也会实际写入数据——当您从容器中弹出一个项目时,容器的大小需要更新,因此推送和弹出都会写入。当多个线程进行写入时,您需要采取一些措施以确保一次只有一个线程进行写入。

总而言之:抱歉,但是没有。

关于c++ - 如果存在仅推送线程和仅弹出线程,C++ std::queue 是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17667202/

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