我正在尝试创建一个世界生成系统。 我有一个世界一流的课程,其中包含可以在程序中增加的地形图。 当我在主线程中执行此操作时,它工作正常,但是当他计算顶点和所有内容时它们几乎没有冻结,所以我尝试使用Thread。
要生成地形,我可以这样做:
sudo chmod -R 755 /var/www/example.com/public
(addTerrain方法)
std::thread newThread(&World::addTerrain, this, xIndex, zIndex, 64, 64);
newThread.detach();
但是当我这样做时,新的地形被添加到地图上,但是他看上去是空的(什么都没画)。
我不确定我是否使用了正确的方法,因此,如果您能帮助我,那就太好了!
答案 0 :(得分:2)
尝试一下:
World
(terrain_mutex_
)std::lock_guard<std::mutex>
进行读/写操作时,请使用allTerrain_
。您的绘画代码也需要使用此互斥锁。addTerrain
中: void World::addTerrain(int x, int z, size_t len, size_t col) {
{ // lock while copying the terrain
std::lock_guard<std::mutex> guard(terrain_mutex_);
auto terrain_copy = allTerrain_;
}
// add more terrain to the copy
terrain_copy[x].emplace(z, Terrain(x*size_, z*size_, size_/2.0f, len, col,
&shader_, &waterShader_, &heightGenerator_));
{ // lock when swapping in the copy
std::lock_guard<std::mutex> guard(terrain_mutex_);
std::swap(terrain_copy, allTerrain_);
}
}