比如有一个类:
class entity
{
public:
int x;
void set_x(int x_)
{
//lock1
x = x_;
}
};vector <entity*> entities;void func()
{
while(1)
{
//lock2
entity* ent = entities[0]; //lock3
ent-> set_x(rand());
}
}int main()
{
entity *ent = new entity();
entities.push_back(ent); thread t1(func());
thread t2(func()); t1.run();
t2.run();
}上面程序的有目的是要修改保存在vector中的对象指针指向的成员变量,那我是应该在vector上,还是对象指针上,还是对象成员变量上加锁呢?
class entity
{
public:
int x;
void set_x(int x_)
{
//lock1
x = x_;
}
};vector <entity*> entities;void func()
{
while(1)
{
//lock2
entity* ent = entities[0]; //lock3
ent-> set_x(rand());
}
}int main()
{
entity *ent = new entity();
entities.push_back(ent); thread t1(func());
thread t2(func()); t1.run();
t2.run();
}上面程序的有目的是要修改保存在vector中的对象指针指向的成员变量,那我是应该在vector上,还是对象指针上,还是对象成员变量上加锁呢?
不过我觉得多线程下应该对共享变量加锁,所以上面的程序中我觉得应该对entities, entity::x这两个加锁,及lock1和lock3我在这里也有提问
http://topic.csdn.net/u/20121020/20/8902774e-c1cf-4f9f-b3ea-f179c83d88af.html?seed=985654257&r=79949038#r_79949038