关于保护全局外部变量的问题

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

我想全局使用这个变量(C,C++)

配置.h

extern YAML::Node m_configList

配置.cpp

YAML::Node m_configList;

这是 yaml-cpp 变量。

这个变量使用了3个文件 文件1.cpp 文件2.cpp 主.cpp

我是否使用互斥锁或其他方式保护这个变量?
如果我保护这个变量,我是否使用全局外部互斥变量来保护它?

c++ mutex extern yaml-cpp
1个回答
0
投票

全局变量的使用是有争议的(如评论所示)。虽然避免全局变量是一种很好的做法,但在某些情况下,尤其是在较小的项目中,它们是有意义的。

几乎肯定应该避免全局变量的一种情况是它可能被多个线程访问。在这种情况下,变量必须受到互斥体的保护。由于必须仔细管理互斥体以避免并发问题,因此必须集中互斥体以及对变量的访问,以确保只有在互斥体锁定的情况下才能访问变量,并确保互斥体在使用后始终处于解锁状态。

因此,变量和互斥体都不应该是全局的。

一个简化的示例(没有错误检查,仅支持字符串值)如下:

config.h:

   ...
   // Config access functions
   std::string getConfig(const std::string key);
   void setConfig(const std::string key, const std::string value);

配置.cpp:

   ...
   static YAML::Node configList;  // Keep variables private to the config module
   static std::mutex configMutex;

   std::string getConfig(const std::string key)
   {
      std::lock_guard<std::mutex>(configMutex);
      return configList[key];
   }

   void setConfig(const std::string key, const std::string value)
   {
      std::lock_guard<std::mutex>(configMutex);
      configList[key] = value;
   }
© www.soinside.com 2019 - 2024. All rights reserved.