This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first:
// Singleton class which contains data class MyData { static MyData* sMyData ; int mData1[1024]; int mData2[1024]; int mData3[1024]; MyData* getInstance() { // sMyData is created in the very beginning. return sMyData ; } void getValues(int idx, int& data1,int& data2,int& data3) { data1 = mData1[idx]; data2 = mData2[idx]; data3 = mData3[idx]; } int* getData1() { return &mData1[0]; } } class MyThread { void workerMethod() { MyData* md = MyData::getInstance(); int d1,d2,d3; md->getValue( 12, d1,d2,d3 ); int* data1 = md->getData1(); d1 = data1[34]; } }
Now as you see I have some getter methods (all read-only), MyData::getInstance(), MyData::getValue() and MyData::getData1(). The 1st question is how thread-safe these methods are ?
Since they are often-called methods, protecting those methods with mutex is something I am trying to avoid.
The 2nd question is: what is the suggested way of reading data from central sources in a multi-thread application, especially in worker methods.
Thanks !
Paul
Provided that no other thread will try to write to the data in your singleton object, you don’t need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program’s initialization code sets up a singleton, which is then only read from by worker threads.
However, if any thread ever writes to this data while others are reading from it, you must protect it in some way. If you have lots of readers and only the occasional writer, it is worth considering some sort of ‘read-write’ lock, which allows multiple readers in the absence of any writers.