C++ Member variable copied for each thread (thread_local-like)

2.6k Views Asked by At

I have an object that during initialization creates several shared memories. The different properties of each shared memory (HANDLE, name, buffer pointer, etc...) are stored in a struct I made and pushed in a vector<SharedMemory>. Once this is done, it creates as many threads on a function MyClass::Server(unsigned int sharedMemoryID) as it created shared memories. sharedMemoryID being the ID of the shared memory in the vector, this way Server() knows which shared memory to use. It then gets ready to serve requests (I use the shared memory as an Inter Process Communication system). This way, each thread uses its own private shared memory and I can treat multiple requests in parallel. I keep the thread stored in a member variable of my class map<unsigned int, thread> m_servers. I also have a function to send requests and responses in the shared memory named MyClass::Send(unsigned int sharedMemoryID, const void* source, unsigned int length)

What I would like is to avoid having to pass the sharedMemoryID at every functions called after Server() since all of the functions related to send and receive can only be called after Server() this is redundant. To do so I would like to have a member variable unsigned int m_serverID that would have its own copy in each thread and that would be written straightaway when Server() gets executed. This way all other functions called afterwards could avoid having sharedMemoryID as argument and jsut get the ID to use from this member variable thread-specific.

I tried to add in my class thread_local unsigned int m_serverID; but it says that thread-local storage class is not valid here. One thing that works is to declare outside my class static thread_local unsigned int serverID; then changing it from my thread, but I would like to have this variable in my object, not being global.

I searched on StackOverflow and on Google and many people seemed to say that what I am looking for make no sense and I have to admit that I don't quite understand why.

Could you tell me if there is a way to have member variables thread-local and if not, could you suggest alternatives and tell me precisely why this is not possible please?

Thank you very much in advance for your help.

0

There are 0 best solutions below