Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
John Humphreys Avatar asked Mar 16 '26 21:03

John Humphreys


2 Answers

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.

like image 63
Greg Hewgill Avatar answered Mar 18 '26 09:03

Greg Hewgill


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.

like image 25
Nicol Bolas Avatar answered Mar 18 '26 10:03

Nicol Bolas