Thread safety for class instance access

53 views Asked by At

In my application, I have the following Worker class (sample/example code):

The instance_ is accessed by WorkerThread's member thread to start/stop timer and read the file names.

class WorkerThread {

   std::thread                                    thread_;
   boost::asio::io_service                        ios_;
   boost::optional<boost::asio::io_service::work> work_;
   std::vector<std::string>                       file_names_vec_;

   static thread_local WorkerThread*             instance_;

   // Some member functions
   void startTimer();
   void stopTimer();
  
   void pushFileNames(std::string filename) {
      file_names_vec_.push_back(filename);
   }


};

And another class as WorkerManager class. Only accessed by the main-thread.

class WorkerManager {

   std::vector<WorkerThread *> WorkerThreadVec_;

   // Some member functions
   void pushFileToThreads(std::string filename) {
      for (auto& worker : WorkerThreadVec_) {
         worker->pushFileNames(filename);
      }
   }

};

The main-thread creates the worker threads by instantiating the WorkerThread class and saves the instance pointers in its vector.

The instance of WorkerManager class gets accessed by the main-thread to add/remove filenames from the WorkerThread instance's data structures. These filenames get read by the member thread_ of WorkerThread using the WorkerThread* instance_.

The member thread_ of WorkerThread also accesses the WorkerThread* instance_ at every 2 seconds to start and stop the timer.

Based on the above design, I have following questions:

  1. Is the thread-safety compromised in above design? Do I need to protect the access to WorkerThread* instance_ to ensure mutual exclusion between the main-thread and the member thread_ of WorkerThread class? The application has not reported any issue in this code flow as of now though.
  2. If I need to protect the access to WorkerThread* instance_, then what should be the best approach considering performance? The member thread_ of WorkerThread would be accessing the WorkerThread* instance_ as fast as every 100 milliseconds. Whereas the main-thread would be accessing it once in 2-3 minutes. I'm just thinking whether a mutex would be costly for the member thread_ of WorkerThread.
0

There are 0 answers