Inline Variables

Using Inline Variables

 #include<iostream>
#include<thread>

struct MyData {
   inline static std::string gName{"global"};           // unique per program
   inline static thread_local std::string tName{"tls"}; // unique per thread
   std::string lName{"local"};                          // unique per object

   void print(const std::string& msg) const {
      std::cout << msg << '\n';
      std::cout << "gName: " << gName << '\n';
      std::cout << "tName: " << tName << '\n';
      std::cout << "lName: " << lName << '\n';
   }
};

inline thread_local MyData myThreadData; // unique per thread

void foo()
{
   myThreadData.print("foo()begin:");
   myThreadData.gName = "thread2 name";
   myThreadData.tName = "thread2 name";
   myThreadData.lName = "thread2 name";
   myThreadData.print("foo() end:");
}

int main() {

   myThreadData.print("main() begin:");
   // main() begin:
   // gName = global
   // tName = tls
   // lName = local

   myThreadData.gName = "thread1 name";
   myThreadData.tName = "thread1 name";
   myThreadData.lName = "thread1 name";

   myThreadData.print("main() later:");
   // main() later:
   // gName = thread1 name
   // tName = thread1 name
   // lName = thread1 name

   std::thread t(foo);
   // foo() begin:
   // gName = thread1 name
   // tName = tls
   // lName = local

   // foo() end:
   // gName = thread2 name
   // tName = thread2 name
   // lName = thread2 name

   t.join();

   myThreadData.print("main() end:");
   // main() end:
   // gName = thread2 name
   // tName = thread1 name
   // lName = thread1 name
}