C++静态函数重复
假设我有一个带有静态函数的类。该类的构造函数使用静态函数作为其入口点执行 pthread_create 。
我的问题是:
如果我有这个类的多个实例,它们都会使用该函数运行自己的线程吗?这样做有什么问题吗?而且......如果函数本身有静态变量,我会遇到它不可重入的问题吗?
Let's say I have a class with a static function. The class's constructor does a pthread_create using the static function as its entry point.
My question is:
If I had multiple instances of this class, would they all run their own thread using that function? Are there any issues with doing this? And... if the function itself had static variables in it, would I have a problem with it not being re-entrant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的构造函数每次都执行
pthread_create()
,那么您将拥有与对象一样多的线程。如果这些线程访问类中的静态变量,您将需要确保对这些变量的访问受到互斥锁的保护。 (此外,如果这些线程访问非静态
变量,您也需要保护这些变量,防止其他调用者访问您的对象的方法)。每个对象一个线程可能太多,因此您可能需要重新考虑您的设计。
If your constructor does a
pthread_create()
every time, then you'll have as many threads as you do objects. If those threads accessstatic
variables in your class, you will need to ensure that access to those variables is protected by a mutex. (Also, if those threads access non-static
variables, you'll want to protect those too, from other callers to your object's methods).One thread per object is probably too many, so you may want to reconsider your design.
是的,所有类都会启动一个具有相同功能的新线程。就像使用非成员函数一样。
至于函数静态变量,这是一个问题。因为 C++ 实际上没有定义任何有关并发的内容,所以您可能会看到竞争条件。即使在这些函数静态变量的构造中也是如此。在 C++0x 支持可用之前,您将需要为您的 CPU 寻找特定于编译器的线程功能,以便您可以告诉它使这些函数静态变量成为“线程本地”。这样,每个线程都会获得自己的副本。
Yes, all of the classes would start a new thread with the same function. Just as they would with using a non-member function.
As for function-static variables, that is a problem. Because C++ doesn't actually define anything about concurrency, you're probably looking at a race condition. Even in the construction of those function-static variables. Until C++0x support is available, you will need to look for compiler-specific threading capabilities for your CPU, so that you can tell it to make those function-static variables "thread local". That way, each thread gets its own copy of them.