好的,所以我有一个结构,在一个单独的线程中不断更新.
现在我需要一些本地的变量,而不需要在它们之间进行更改.
我第一次这样做是为了让它们在本地获得,这显然不是最好的方法,但它有效.
float MyFloatArray[3];
MyFloatArray[0] = otherThread()->floatArray[0];
MyFloatArray[1] = otherThread()->floatArray[1];
MyFloatArray[2] = otherThread()->floatArray[2];
Run Code Online (Sandbox Code Playgroud)
现在我想知道是否有更好的方法来做到这一点.
我已经尝试过以下方法:
float MyFloatArray = otherThread()->floatArray;
float* MyFloatArray = otherThread()->floatArray; //Works but updates the otherThread array(Obviously) but that shouldn't happen
Run Code Online (Sandbox Code Playgroud)
由于我有一个相当大的项目,所以要将所有这些更新为很多工作 std::array<float,3>
还有其他选择吗?否则我将更新我的所有浮点数组,std::array<float,3>因为如果没有替代方案它会更清洁.
您可以简单地调用std::copy,确保副本由同步机制(如a)保护mutex.例如:
std::mutex m; // otherThread() must lock this mutex when modifying array
{
std::lock_guard<std::mutex> lock(m);
std::copy(otherThread()->floatArray, otherThread()->floatArray + 3, MyLoatArray);
}
Run Code Online (Sandbox Code Playgroud)
或使用可复制的类型,例如std::array<float, 3>并使用赋值.同样,必须使用同步机制保护它:
std::mutex m; // otherThread() must lock this mutex when modifying array
{
std::lock_guard<std::mutex> lock(m);
MyFloatArray = otherThread()->floatArray;
}
Run Code Online (Sandbox Code Playgroud)