我需要用非常量元素锁定 const 容器吗?

问题描述 投票:0回答:1

我开发了一个多线程应用程序(用 C++ 开发),它具有各种集合,其中容器(向量、映射等)在初始化时是 const,但容器中的元素不是 const。

我想知道在从容器中检索元素并对其进行读取/写入时是否需要始终保持锁定,或者仅在读取/写入时锁定就足够了......我只是想解决/避免一些死锁问题,如果我在迭代集合时不必持有锁,这些问题就可以解决。

这是一个简单的例子,我在这个例子中的问题是围绕GetObject和AdjustValue函数的锁定过程。如果这是一个多线程应用程序,理想情况下我只想在调用调整值时锁定,并且仅在调整集合中特定元素的数据时锁定。我认为这没问题,因为集合是 const(填充集合后,不会添加、删除或删除对象)。

自定义类.h

class CustomClass
{
public:
   CustomClass() : 
      m_value(0)
   {

   }

   int m_value;
};

自定义集合

#include "CustomClass.h"
#include <vector>

class CustomCollection
{
public:
   CustomCollection() : 
      m_collection(CreateCustomCollection())
   {

   }

   CustomClass* GetObject(
      const size_t index)
   {
      // Should I lock here, or since the collection is const can I avoid locking?
      if(index >= 0 && index < m_collection.size())
      {
         return m_collection[index];
      }

      return nullptr;
   }

   void AdjustValue()
   {
      // Do I need to lock before calling GetObject?
      // Since the collection is const, can I lock only when adjusting the values of the object itself?
      CustomClass* custom_object = GetObject(0);
      if(custom_object)
      {
         // Ideally I only need to lock here since the collection is const, just not the objects.
         custom_object->m_value++;
      }
   }
private:
   static const std::vector<CustomClass*> CreateCustomCollection()
   {
      std::vector<CustomClass*> collection;
      collection.push_back(new CustomClass());

      return collection;
   }

   const std::vector<CustomClass*> m_collection;
};
c++ thread-safety locking deadlock
1个回答
0
投票

m_collection
实际上是一个常量对象,它本身在构造后永远不会被修改。因此,访问此容器不需要锁定。

         // Ideally I only need to lock here since the collection is const, just not the objects.
         custom_object->m_value++;

正确,如果从多个执行线程访问

m_value
,则对
m_value
的所有访问都必须正确同步。

© www.soinside.com 2019 - 2024. All rights reserved.