吸气功能是否需要互斥体? [英] Does a getter function need a mutex?

查看:105
本文介绍了吸气功能是否需要互斥体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以从多个线程访问的类.它的getter和setter函数均由锁保护.

I have a class that is accessed from multiple threads. Both of its getter and setter functions are guarded with locks.

真的需要getter函数的锁吗?如果是这样,为什么?

Are the locks for the getter functions really needed? If so, why?

class foo {
public:
    void setCount (int count) {
        boost::lock_guard<boost::mutex> lg(mutex_);
        count_ = count;
    }

    int count () {
        boost::lock_guard<boost::mutex> lg(mutex_); // mutex needed?
        return count_;
    }

private:
    boost::mutex mutex_;
    int count_;
};

推荐答案

获得锁的唯一方法是,如果您可以说服自己,系统将在所有情况下自动转移受保护的变量.如果由于一个或另一个原因不能确定这一点,则需要互斥量.

The only way you can get around having the lock is if you can convince yourself that the system will transfer the guarded variable atomicly in all cases. If you can't be sure of that for one reason or another, then you'll need the mutex.

对于像int这样的简单类型,您可以说服自己是对的,具体取决于体系结构,并假定它已正确对齐以进行单指令传输.对于任何比这更复杂的类型,您都将必须具有锁.

For a simple type like an int, you may be able to convince yourself this is true, depending on architecture, and assuming that it's properly aligned for single-instruction transfer. For any type that's more complicated than this, you're going to have to have the lock.

这篇关于吸气功能是否需要互斥体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆