小编jac*_*ack的帖子

如何在C++ 11中实现自己的读/写锁?

我有一组数据结构,我需要用读/写锁来保护.我知道boost :: shared_lock,但我想使用std :: mutex,std :: condition_variable和/或std :: atomic进行自定义实现,这样我就能更好地理解它是如何工作的(稍后再调整) .

每个数据结构(可移动但不可复制)将从一个名为Commons的类继承,该类封装了锁定.我希望公共接口看起来像这样:

class Commons {
public:
    void read_lock();
    bool try_read_lock();
    void read_unlock();

    void write_lock();
    bool try_write_lock();
    void write_unlock();
};
Run Code Online (Sandbox Code Playgroud)

...以便某些人可以公开继承:

class DataStructure : public Commons {};
Run Code Online (Sandbox Code Playgroud)

我正在编写科学代码,通常可以避免数据争用; 这种锁定主要是为了防止我以后可能犯的错误.因此,我的优先级是低读取开销,所以我不会妨碍正确运行的程序太多.每个线程可能都在自己的CPU核心上运行.

你能告诉我(伪代码是好的)读者/作家锁吗?我现在所拥有的应该是防止作家饥饿的变种.到目前为止,我的主要问题是read_lock在检查读取是否可以安全地实际递增读取器计数之间的差距,之后write_lock知道等待.

void Commons::write_lock() {
    write_mutex.lock();
    reading_mode.store(false);
    while(readers.load() > 0) {}
}

void Commons::try_read_lock() {
    if(reading_mode.load()) {
        //if another thread calls write_lock here, bad things can happen
        ++readers; 
        return true;
    } else return false;
}
Run Code Online (Sandbox Code Playgroud)

我对多线程有点新意,我真的很想理解它.在此先感谢您的帮助!

c++ multithreading locking readwritelock c++11

38
推荐指数
2
解决办法
4万
查看次数

如何测试函数的平等性或身份?

我希望能够测试两个可调用对象是否相同.我更喜欢身份语义(使用"是"运算符),但我发现当涉及方法时,会发生不同的事情.

#(1) identity and equality with a method
class Foo(object):
    def bar(self):
        pass
foo = Foo()
b = foo.bar
b == foo.bar    #evaluates True. why?
b is foo.bar    #evaluates False. why?
Run Code Online (Sandbox Code Playgroud)

我用Python 2.7和3.3(CPython)重现了这一点,以确保它不是旧版本的实现细节.在其他情况下,身份测试按预期工作(翻译会议从上面继续):

#(2) with a non-method function
def fun(self):
    pass
f = fun
f == fun    #evaluates True
f is fun    #evaluates True

#(3) when fun is bound as a method 
Foo.met = fun
foo.met == fun    #evaluates False
foo.met is fun    #evaluates False

#(4) with a callable data …
Run Code Online (Sandbox Code Playgroud)

python

17
推荐指数
1
解决办法
794
查看次数

标签 统计

c++ ×1

c++11 ×1

locking ×1

multithreading ×1

python ×1

readwritelock ×1