I have a number of worker threads, all taking jobs from a queue. The jobs use several objects which must access a structure from a non thread-safe third-party library - so each thread ideally needs its own structure. Could anyone suggest a way of giving the objects access to the shared structure?
The structure is actually the state of a RNG, so I'd rather not initialise a new one in each class where it's needed as its expensive. I'm tempted to use a singleton with Boost thread-local storage, something like this:
class RandomGenerator
{
public:
static RandomGenerator* instance()
{
boost::thread_specific_ptr<RandomGenerator> threadInstance;
if(threadInstance.get() == 0)
threadInstance.reset(new RandomGenerator());
return threadInstance;
}
/* Return the actual structure. */
gmp_randstate_t& getState() const
{
return m_state;
}
private:
RandomGenerator() { /* etc. */ }
mutable gmp_randstate_t m_state;
};
It seems messy and I'd rather not use a singleton if possible.
Any suggestions are appreciated!
Thanks.