静态成员函数和线程安全
在 C++ 中,当静态成员函数中有局部变量时,这是否意味着这些局部变量也是隐式静态的或者它们确实是局部的?
示例:
static void myClass::somefunc(int someint)
{
int myint = someint; // is myint really a local variable or does it change due to the static qualifier at function level?
}
另外,运行此函数的线程池中的不同线程是否需要使用锁保护 myint ?假设传递给它的所有值都是不同的并且彼此没有关系。
编辑:感谢您的回答。现在,如果我传入一个 boost::shared_ptr
,并且知道该对象不会同时被另一个线程使用,该怎么办? (不确定是否真的可以保证这一点,或者你可以吗?)
我猜传入的原始 ptr 是否需要一些保护,如果它被到处使用?
In C++, when you have local variables in a static member function, does it mean those local variables are also implicitly static or are they really local?
example:
static void myClass::somefunc(int someint)
{
int myint = someint; // is myint really a local variable or does it change due to the static qualifier at function level?
}
Also, different threads from a thread pool running this function, does myint need to be protected by a lock? assuming that all values passed to it are different and have no relation to each other.
EDIT: Thanx for the answers. Now what if I passed in a boost::shared_ptr<T>
, knowing that this object would not be concurrently being used by another thread? (Not sure if one can really guarantee that, or can you?)
I guess a raw ptr passed in, would need some protection, if it were being used all over?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它们是本地的,除非您将它们声明为
静态
- 函数的每次调用都将拥有自己的变量副本,并且您不需要保护它们。They are local unless you declare them
static
- each invokation of the function will have its own copy of the variable and you don't need to to protect them.myint
是somefunc
的本地变量,您不需要跨线程保护它。myint
is local forsomefunc
and you don't need to protect it across threads.你的例子中的 myint 是一个局部变量,每次 somefunc 被调用 myint 时都会存在。但仅此而已。
myint 不需要保护,因为它是局部变量
myint in your example is a local variable, every time somefunc is called myint lives. but not more than that.
myint doesn't need to be protected because its a local variable
myint
将真正成为本地的。您不必担心保护它。对于内存中的每个函数调用,都会在堆栈上为myint
创建一个单独的空间。myint
will truly be local. You don't have to worry about protecting it. A separate space will be created on the stack formyint
for every single function call in memory.myint
变量将保留在本地,无需保护它们,因为每个线程不会共享本地变量。The
myint
variable will stay local, there is no need to protect them since each thread will not share the local variables.static 关键字意味着该函数不会传递隐藏的“this”
争论。该函数也将无权访问类实例数据。
函数的静态限定符,对函数的本地数据没有影响。
static RetType SomeClass::SomeMethod(Type arg)
与自由函数具有相同的“类型”RetType SomeFunc(Type arg)
此致,
马尔辛
The static key-word means that the function will not be passed a hidden "this"
argument. Also the function will not have access to the class instance data.
The static qualifier of function, has no impact on function's local data.
The
static RetType SomeClass::SomeMethod(Type arg)
has the same "type" as a free functionRetType SomeFunc(Type arg)
Regards,
Marcin