Consider the below testcase:
#include <iostream>
#include <thread>
thread_local struct Bar
{
Bar() { std::cout << '*' << std::endl; }
~Bar() { std::cout << '~' << std::endl; }
} bar;
struct Foo
{
void baz()
{
(void)&bar;
}
};
int main()
{
Foo f;
f.baz();
std::thread t(&Foo::baz, &f);
t.join();
}
On Coliru it works as I intend, with the seemingly useless statement (void)&bar
apparently counting as "use" and ensuring that bar
is constructed in any thread that invokes baz()
.
Is this guaranteed, or should I do something more?
I'm hoping to use a class like Bar
to wrap some per-thread initialisation required by a C library I'm going to use, with a minimum of boilerplate. baz()
is already a function that any thread will call to do work with the C library, so this could effectively be a transparent solution.