将2个指针传递给2个线程,但它们最终共享相同的内容

 mobiledu2502856973 发布于 2023-02-13 19:22

我想这个问题已经出现了,它肯定会在线程世界中显示我的初学者级别,但我无法找到任何先前的问题或其他资源来解决它.我已经完成了对C++ 11线程最常见的介绍(比如这个,这个和这个),但它没有帮助.

这是我的代码:

mutex mtx;
vector threads;

for(vcit = vc.begin(); vcit != vc.end(); ++vcit) {
    const std::shared_ptr g = graphs.at(*vcit);

    cout << "Graph (outside thread): " << g->name << endl;
    threads.push_back(thread(
        [&g, &mtx] () {
            lock_guard guard(mtx);
            cout << "Graph (inside thread): " << g->name << endl;
        }
    ));
}

for(thread& t : threads) {
    t.join();
} 

我希望每个线程都接收不同的指针,但是程序的输出如下(对于向量中的2个元素vc):

Graph (outside thread): ABC
Graph (outside thread): DEF
Graph (inside thread): DEF
Graph (inside thread): DEF

有时程序会"工作"并输出:

Graph (outside thread): ABC
Graph (inside thread): ABC
Graph (outside thread): DEF
Graph (inside thread): DEF

(注意现在外部和内部输出的混合顺序).我试图从lambda转移到functor对象,但这没有任何帮助,程序表现出相同的行为.

我想知道问题在哪里,代码以及我对线程(或者shared_ptr可能)如何工作的理解是有缺陷的,如果这可以从代码中推断出来的话.

1 个回答
  • lambda g通过引用捕获,实际上是存储指向仅存在于for循环内部的内存的指针.虽然它没有定义行为,因为内存在堆栈上,但两个地址的概率相同.因此,有时两个线程将读取相同的值,有时它们将读取不同的值 - 有时它们甚至可以读取垃圾值.

    2023-02-13 19:25 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有