静态成员函数和线程安全 [英] static member function and thread-safety

查看:94
本文介绍了静态成员函数和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,当静态成员函数中具有局部变量时,是否意味着这些局部变量也是隐式静态的,或者它们确实是局部的?

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?

示例:

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是否需要由锁保护?假设传递给它的所有值都是不同的,并且彼此之间没有任何关系.

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.

感谢您的回答.现在,如果我传入了boost::shared_ptr<T>,又知道另一个线程不会同时使用该对象,该怎么办? (不确定是否可以真正保证这一点,或者可以吗?)

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?)

我想传入一个原始的ptr,如果它被全部使用,是否需要一些保护?

I guess a raw ptr passed in, would need some protection, if it were being used all over?

推荐答案

除非您声明static,否则它们是局部的-函数的每次调用都将具有其变量的自己的副本,并且您无需保护他们.

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.

这篇关于静态成员函数和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆