-1

I am calling a member function inside the thread. I have a member variable that I edit inside this function for which I have applied the lock. Is this logic okay or do even the reads need to be thread-safe?

The code is something like the one shown below:

#include <iostream>
#include <vector>
#include <mutex>
#include <future>
#include <memory>
using namespace std;

class A
{
   int occurrence;
   mutex m;
public:
   A() = default;
   void operation()
   {
      /*--
      Some operations where I only read the class members other than occurrence but do not modify them.
--*/
      {
         lock_guard<mutex> my_lock(m);
         occurence++;
      }
   }
   int getOccurence()
   {
      return occurence;
   }
};

class B
{
   shared_ptr<A> a{};
public:
   B(shared_ptr<A>& a_ptr)
   {
      a = a_ptr;
   }
   void callAoperation()
   {
      a->operation();
   }
};



int main()
{
   shared_ptr<A> a = make_shared<A>();
   B* b = new B(a);
   vector<std::future<void>> async_call;
   int i = 0;
   while (i < 10)
   {
      async_call.push_back(async(launch::async, &B::callAoperation, b));
      i++;

   }
   for (auto&& fut : async_call)
   {
      fut.wait();
   }
   cout << a->getOccurence();

}

Inside my operation method, I modify only one variable, others I just read. The class variable which I am modifying is inside a lock.

I want to know, Is this logic correct or will it have some issues?

  • Your code can't be compiled due to missing includes, namespaces and other syntax errors. Your code is not a [mcve] and will be likely downvoted because of unrespect to SO users. – 273K Jun 26 '22 at 06:45
  • No reading a member variable isn't guaranteed to be threadsafe. If you only have to keep one value threadsafe have a look at https://stackoverflow.com/questions/31978324/what-exactly-is-stdatomic – Pepijn Kramer Jun 26 '22 at 07:15

1 Answers1

0

The logic is not correct. While reading a variable, another thread can modify it, leading the data race. You should use std::shared_mutex and protect reading from writing using std::shared_lock, prevent writing while reading with std::unique_lock.

273K
  • 29,503
  • 10
  • 41
  • 64