簡體   English   中英

C++:在線程中使用指針調用另一個類的方法安全嗎?

[英]C++ : Is calling a method of another class using pointer in a thread safe?

我在線程內調用一個成員函數。 我有一個在這個函數中編輯的成員變量,我已經為其應用了鎖。 這個邏輯可以嗎,或者甚至讀取都需要是線程安全的?

代碼類似於如下所示:

#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();

}

在我的操作方法中,我只修改了一個變量,其他的我只是讀取。 我正在修改的類變量在鎖內。

我想知道,這個邏輯是正確的還是會有一些問題?

邏輯不正確。 在讀取變量時,另一個線程可以修改它,從而導致數據競爭。 您應該使用std::shared_mutex並使用std::shared_lock防止讀取寫入,使用std::unique_lock讀取時防止寫入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM