#include <iostream>
#include <mutex>
#include <string>
#include <thread>
class ThreadLocalSingleton {
private:
ThreadLocalSingleton() {
std::cout << "created for thread " << std::this_thread::get_id()
<< std::endl;
}
ThreadLocalSingleton(const ThreadLocalSingleton&) = delete;
ThreadLocalSingleton& operator=(const ThreadLocalSingleton&) = delete;
public:
static ThreadLocalSingleton& getInstance() {
thread_local ThreadLocalSingleton instance;
return instance;
}
void doSomething(std::string msg) {
std::cout << msg << " from thread " << std::this_thread::get_id()
<< std::endl;
}
};
thread_local unsigned int rage = 1;
std::mutex cout_mutex;
void increase_rage(const std::string& thread_name) {
++rage; // modifying outside a lock is okay; this is a thread-local
// variable
ThreadLocalSingleton::getInstance().doSomething(thread_name);
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}
int main() {
std::thread a(increase_rage, "a"), b(increase_rage, "b");
{
ThreadLocalSingleton::getInstance().doSomething("main");
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for main: " << rage << '\n';
}
a.join();
b.join();
}
// https://www.online-cpp.com/
// created for thread 140557953695048
// main from thread 140557953695048
// Rage counter for main: 1
// created for thread 140557951163168
// b from thread 140557951163168
// Rage counter for b: 2
// created for thread 140557951306528
// a from thread 140557951306528
// Rage counter for a: 2