如何解决C++代码运行时出现的thread线程相关报错问题?
问题根因
代码创建线程时绑定的是临时构造的GridWorld对象,而非你预先声明、持有运行状态的world实例,多线程操作的对象与实际逻辑使用的对象完全割裂,状态不一致触发运行时错误。
具体错误点
thread render(&GridWorld::Render, GridWorld())中第二个参数GridWorld()会生成全新的临时GridWorld对象,线程仅操作这个临时对象,执行完毕后临时对象直接销毁,你后续调用world.GetInput()时使用的world实例从未被渲染或更新。- 更新线程同理,
thread thread_update(&GridWorld::Update, GridWorld())操作的是另一个独立的临时对象,和你声明的world无任何关联。 - 额外逻辑问题:线程创建后立刻调用
join(),程序会卡住等待线程执行完再走下一步,完全没有利用多线程并行能力。
修复方案
将线程绑定的对象替换为你预先声明的world实例的指针即可:
#include <iostream> #include <thread> #include <string> // 确保已引入GridWorld相关头文件 { GridWorld world; std::string input = ""; while (input != "q") { std::thread render(&GridWorld::Render, &world); render.join(); input = world.GetInput(); std::thread thread_update(&GridWorld::Update, &world); thread_update.join(); } std::cout << "Thank you for playing\n"; }
如果需要实现渲染和更新并行运行,可以调整线程启动和join的顺序,同时注意给GridWorld内部共享数据加互斥锁避免读写冲突:
// 并行版本示例 while (input != "q") { std::thread render(&GridWorld::Render, &world); std::thread thread_update(&GridWorld::Update, &world); // 等待两个线程都执行完成 render.join(); thread_update.join(); input = world.GetInput(); }
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

