Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/141.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 功能的优雅互斥开关开/关?_C++_Templates_Mutex - Fatal编程技术网

C++ 功能的优雅互斥开关开/关?

C++ 功能的优雅互斥开关开/关?,c++,templates,mutex,C++,Templates,Mutex,你能想出一种优雅的方法用可选的互斥锁锁创建(成员)函数吗?出于显而易见的原因,让我们忽略宏 当然,最简单的方法是拥有两个功能: int getIndex() const { std::lock_guard m( mtx ); return nm_getIndex(); } int nm_getIndex() const { return _index; } 这将创建高效的代码,但它依赖于代码复制。基本上,大多数函数声明都会有两次 另一种方法是将它们转换为模板函数。布尔模板参数将用作“en

你能想出一种优雅的方法用可选的互斥锁锁创建(成员)函数吗?出于显而易见的原因,让我们忽略宏

当然,最简单的方法是拥有两个功能:

int getIndex() const    { std::lock_guard m( mtx ); return nm_getIndex(); }
int nm_getIndex() const { return _index; }
这将创建高效的代码,但它依赖于代码复制。基本上,大多数函数声明都会有两次

另一种方法是将它们转换为模板函数。布尔模板参数将用作“en-/disabler”。然后可以像这样调用函数:

auto index = getIndex< NoMutex >();
目前我唯一能想到的就是围绕互斥体构建一个类,并将其放入一个联合体中。然后,该类可以“玩锁护”或什么都不做。虽然我很确定这会在发布代码中得到适当的优化,但它看起来仍然很麻烦且不灵活。 因此,我想知道你是否能想出更好的办法


谢谢

我能想到的最简单的方法是:

  • 创建一个noop lock_guard类

  • 创建一个模板函数,该函数始终使用指定为模板参数类型的锁防护装置

  • 当您想要一个非阻塞版本的函数时,您可以传入noop-guard

  • 例如:

    template<typename Guard>
    int getIndex<Guard>() const    { Guard m( lock ); return nm_getIndex(); }
    
    class NoopLockGuard ; //dummy class. it does absolutely nothing
    int i = getIndex<NoopLockGuard>()
    int j = getIndex<std::lock_guard>()
    
    模板
    int getIndex()常量{Guard m(lock);返回nm_getIndex();}
    门卫类//虚拟类。它完全不起作用
    inti=getIndex()
    int j=getIndex()
    

    编译器应该能够使用
    NoopLockGuard
    优化版本,以使其产生最小或零的性能损失。

    当然有明显的模板专门化方法,但这会导致对一个操作使用多个方法,正如您自己所说的那样。“唯一的ptr-to-lock-guard”该方法与unionionized版本大致相同,但它增加了内存分配。谢谢,看起来确实不错。您甚至可以通过其他锁防护,如作用域锁等:-)
    template<typename Guard>
    int getIndex<Guard>() const    { Guard m( lock ); return nm_getIndex(); }
    
    class NoopLockGuard ; //dummy class. it does absolutely nothing
    int i = getIndex<NoopLockGuard>()
    int j = getIndex<std::lock_guard>()