开发者

C++ Static function duplication

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?


If your constructor does a pthread_create() every time, then you'll have as many threads as you do objects. If those threads access static 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜