c++ - 与 std::vector<>::size() 并发

标签 c++ multithreading c++11 vector

此代码挂起(请注意,仅在发布版本中)并且必须手动终止:

#include <Windows.h>
#include <vector>
#include <thread>

int main()
{
    std::vector<int> vec;
    vec.push_back( 0 );
    std::thread( [&vec]()
    {
        Sleep( 150 );
        vec.pop_back();
    } ).detach();
    while( vec.size() > 0 );
    return 0;
}

而这段代码自然终止:

#include <Windows.h>
#include <vector>
#include <thread>

int main()
{
    std::vector<int> vec;
    vec.push_back( 0 );
    std::thread( [&vec]()
    {
        Sleep( 150 );
        vec.pop_back();
    } ).detach();
    while( vec.size() > 0 )
    {
        Sleep( 1 );
    }
    return 0;
}

似乎连续发送std::vector<int>::size() 的垃圾邮件以某种方式阻止执行,但是如何以及为什么?为什么只在发布版本中?

(使用 VC2013 构建,如果这是一个因素。)

最佳答案

最可能的解释是优化器改变了循环:

while (vec.size() > 0);

进入

reg = vec.size(); while(reg > 0);

...将 vec.size() 中的值加载到一个寄存器中,然后从那里读取它,因为循环中没有任何内容表明可能导致该值的内存屏障多变。

当您在循环中调用 Sleep 时,该调用涉及溢出寄存器,因此将值保存在寄存器中没有任何好处,因此未完成。

关于c++ - 与 std::vector<>::size() 并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33621444/

相关文章:

c++ - 多次对 vector 进行排序

c - pthread_rwlock_rdlock() 和 pthread_rwlock_wrlock()

windows - std::condition_variable notify_all 不会同时唤醒所有线程

c++ - 如何判断您的编译器支持哪个版本的 ISO C++ 标准?

c++ - 为什么在 "SND_SYNC"中使用 "QueueUserWorkItem"坏?

c++ - 如何使用 Doxygen 记录具有相同名称的枚举值?

c++ - 立即在不同的线程上通过 IP 发送

c++ - 在较新的 Ubuntu 版本中为旧的 Ubuntu 版本编译 C/C++

c++ - 如何最小化控制台窗口?

c++ - 在 C++ 中线程化以保持两个函数并行运行