What is the problem with having static variables (especially within functions) in multithreaded programs?
Thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To pick an illustrative example at random, take an interface like
asctimein the C library. The prototype looks like this:This implicitly must have some global buffer to store the characters in the
char*returned. The most common and simple way to accomplish this would be something like:This is totally broken in a multi-threaded environment, because
bufwill be at the same address for each call toasctime(). If two threads callasctime()at the same time, they run the risk of overwriting each other’s results. Implicit in the contract ofasctime()is that the characters of the string will stick around until the next call toasctime(), and concurrent calls breaks this.There are some language extensions that work around this particular problem in this particular example via thread-local storage (
__thread,__declspec(thread)). I believe this idea made it into C++0x as thethread_localkeyword.Even so I would argue it’s a bad design decision to use it this way, for similar reasons as for why it’s bad to use global variables. Among other things, it may be thought of as a cleaner interface for the caller to maintain and provide this kind of state, rather than the callee. These are subjective arguments, however.