Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are C++ static variables always destructed on main thread?

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)

like image 478
tower120 Avatar asked Nov 09 '17 17:11

tower120


People also ask

Is static variable shared between threads in C?

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.

Are static variables shared between threads?

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.

Is static thread-safe C?

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.

Are static variables stored on heap in C?

The static variables are stored in the data segment of the memory.


1 Answers

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.

like image 176
Maxim Egorushkin Avatar answered Sep 30 '22 17:09

Maxim Egorushkin