c ++ 11线程不修改相同的值 [英] c++11 threads don't modify same values
问题描述
我正在写一个程序(理想情况下)需要两个线程同时运行。
I'm writing a program that (ideally) requires two threads to run simultaneously.
我有一个全局矢量变量myObjects来跟踪我的对象: / p>
I have a global vector variable myObjects to keep track of my Objects:
vector<Object> myObjects;
类型 MoND
的对象做重型起重。
它以向量作为参数初始化,并将Objects推入向量。到目前为止没有问题。
And a object of type MoND
that will be doing the heavy lifting.
It is initialized with the vector as an argument and it pushes "Objects" into the vector. No problem so far.
MoND mySim = MoND(myObjects);
在main中,mySim的方法需要调用 myObjects
作为参数。
在用于测试的非线程版本中,这样工作(在100次迭代后运行bails):
In main, a method of mySim needs to be called with myObjects
as an argument.
In a non-threaded version I used for testing, this works (run bails out after 100 iterations):
int main(int argc, char** argv) {
...
mySim.Run(myObjects);// Run simulation on Objects
glutMainLoop(); // Enter the event-processing loop
return 0;
}
通过工作我的意思是改变 Object
存储在 myObjects
中。
By works I mean changes the properties of the Object
s stored in myObjects
.
This needs to run persistently and concurrently so it's not ideal.
使用线程:
int main(int argc, char** argv) {
...
thread t1(&MoND::Run, mySim, myObjects);// Run simulation on Objects
glutMainLoop(); // Enter the event-processing loop
return 0;
}
这没有所需的效果。
Run()
接收myObjects并更改它们的值,但这些不会转换为 myObjects
由主线程。是否在新线程的内存中创建了 myObjects
的另一个实例?
(是的,我通过引用和非线程版本更新的值很好)
This doesn't have the desired effect.
Run()
receives myObjects and changes their values, but these are not translated to the myObjects
being used by the main thread. Is another instance of myObjects
created in memory for the new thread?
(yes, I did pass by reference and the non-threaded version does update the values just fine)
所以我知道逻辑工作预期没有线程)。
我试图使用原子但坦率地说,我不能得到它使用一个向量或其内容。
So I know the logic works (everything works as expected without threading). I have tried to use atomic but to be honest I can't get it to work with a vector or its contents.
如何强制两个线程来处理内存中 myObjects
的同一个实例(即让它们共享变量)?
How can I force the two threads to work on the same instance of myObjects
in memory (i.e. get them to share the variable)?
分数:
-
不,我不担心线程安全性,因为只有一个线程写入,读/写是不重要的)
No, I'm not worried about thread safety as only one thread writes, the other just reads (order of reading/writing is unimportant)
Run()
更新类的对象中的私有变量的值对象通过方法 SetPos(args ..)
和 SetVel(args ..)
Run()
updates the values of private variables in objects of class Object through methods SetPos(args..)
and SetVel(args..)
推荐答案
std :: thread
为了避免这种情况,你可以使用 std :: ref
:
To avoid that, you can use std::ref
:
thread t1(&MoND::Run, mySim, std::ref(myObjects));
这里你承诺照顾你的对象的一生。
Here you promise that you take care of your object's lifetime.
std :: bind
和 std :: async
。
请注意, mySim
也正在被复制,但这里你也可以传递一个指针,如果不想复制。
Note that mySim
is also being copied, here however you could also pass a pointer if don't want the copy.
这篇关于c ++ 11线程不修改相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!