C++ 创建原子函数

Kol*_*nya 5 c++ multithreading pointers mutex atomic

void foo ( Bar* bar , void(Bar::*qux)(void) )
{
    if ( bar )
    {
        bar->qux();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是:

  1. bar可以在其他线程检查删除。

  2. 我无法添加互斥锁成员Bar来锁定它。

因此我想知道,如果我可以告诉处理器原子地运行这个函数,我该怎么做?我在谷歌上花了很多时间,但没有找到可以理解的手册......

PS的Debian,GCC,增压NOT允许,C ++ 11 IS允许的。

Bra*_*ady 2

原子方法的概念在 C++ 中并不像在 Java 中那样存在,在 Java 中您可以将方法定义为同步。在 C++ 中最接近的做法是创建一个 ScopedMutex 类,如下所示:

class ScopedMutex {
public:
    ScopedMutex(pthread_mutex *m) : theMutex_(m) {pthread_mutex_lock(theMutex_);}
    ~ScopedMutex() { pthread_mutex_unlock(theMutex_); }
    // Add appropriate copy constructors and operator=() to disallow mutex copy
    // Or consider passing in a reference
private:
    pthread_mutex *theMutex_;
};
Run Code Online (Sandbox Code Playgroud)

然后在你的函数中像这样使用它:

void foo ( Bar* bar , void(Bar::*qux)(void) )
{
    ScopedMutex m(&aMutex); // This mutex must be defined/initialized elsewhere

    if ( bar )
    {
        bar->qux();
    }

    // The ScopedMutex goes out of scope when the function does,
    // thus releasing the lock
}
Run Code Online (Sandbox Code Playgroud)

但这不会给您带来任何好处,除非您在使用 bar 对象的每个其他方法中使用相同的互斥锁。

当您的函数具有复杂的逻辑且有多个 return 语句时,作用域互斥体特别有用,因此您不必手动解锁互斥体,当函数超出作用域时,它就会被解锁。

  • @nogard,Ugg,抱歉,我试图同时做太多事情,太多的上下文切换不仅对计算机有害:) (3认同)