Short question:
Are C++11 static (non thread_local) variables always destructed on main thread?
Are they always destroyed on program exit only (considering we do not call manually their destructors)?
UPDATE
For brevity, lets assume that destructors ARE called. (we did not pull the plug, we did not kill -9)
Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
Static variables are indeed shared between threads, but the changes made in one thread may not be visible to another thread immediately, making it seem like there are two copies of the variable.
No, static functions are not inherently thread-safe. Even your simple example isn't. Assuming both intvariable and stringvariable are supposed to be updated at the same time, another thread could observe the state of c1 between the two assignments, leading to data corruption.
The static variables are stored in the data segment of the memory.
Destructors of the global objects are called by std::exit
. That function is called by the C++ run-time when main
returns.
It is possible to arrange for std::exit
to be called by a thread other than that which entered main
. E.g.:
struct A
{
A() { std::cout << std::this_thread::get_id() << '\n'; }
~A() { std::cout << std::this_thread::get_id() << '\n'; }
};
A a;
int main() {
std::thread([]() { std::exit(0); }).join();
}
Outputs:
140599080433472
140599061243648
Showing that one thread called the constructor and another the destructor.
See std::exit
and std::atexit
for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With