Search code examples
c++winapisingletonposixmacos-carbon

Limiting Singleton instance to thread


What is a good way to implement a singleton that will be restricted only to the thread that seeks its instance? Is there a thread id or something that I can use to do that? I'm using Carbon threading API but will have to implement this on windows and pure POSIX later too, so any technique is appreciated.


Solution

  • In the past, I have leveraged a hashmap or index to store data structures that are per-thread inside of a single global thread-safe data structure. For instance, if you provide the id for each thread as an incrementing integer, you can store your data structure in a pre-allocated array at the index of the thread it. If you are leveraging thread IDs that are provided by the operating system or need to be more flexible, then a thread safe HashMap or HashTable will come in quite handy.

    Jacob