多线程:我需要保护我的变量在只读方法? [英] Multithreading: do I need protect my variable in read-only method?

查看:186
本文介绍了多线程:我需要保护我的变量在只读方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎没有关于使用锁来保护我共享的数据结构的问题。我使用C / C ++ / ObjC / Objc ++



例如我有一个在多线程环境中使用的计数器类

  class MyCounter {
private:
int counter;
std :: mutex m;

public:
int getCount()const {
return counter;
}
void increase(){
std :: lock_guard< std :: mutex> lk(m);
counter ++;
}
};




  1. 我需要使用 std :: lock_guard< std :: mutex>


  2. li>

    如果只有两个线程会发生什么:读者线程和写线程,然后我必须保护它吗?因为只有一个线程正在修改变量,所以我认为不会丢失更新。


  3. 如果共享的原始类型变量有多个writer / reader (例如 int )如果我只锁定写入方法但没有读取方法,会发生什么灾难?


  4. 默认情况下,任何原始类型都是原子类型吗?例如写入 char 总是原子的? (我知道这是真的在Java,但不知道关于c + +和我使用llvm编译器在Mac如果平台重要)



解决方案

是的,除非你能保证基础变量 counter 的变化是原子的,你需要互斥。 p>

经典的例子,说 counter 是一个两字节的值,在(非原子)阶段递增:

 向低字节添加1 
如果低字节为0:
将1添加到高字节



,初始值为255。



在低字节变化和高字节变化之间的任何地方,它将读取0而不是正确的255(预增量)或256(后增量)。



对于什么数据类型是原子的,最新的C ++标准在< atomic> 头中定义它们。

如果你有C ++ 11的能力,那么实现什么类型是原子的。


I have few questions about using lock to protect my shared data structure. I am using C/C++/ObjC/Objc++

For example I have a counter class that used in multi-thread environment

class MyCounter {
private:
    int counter;
    std::mutex m;

public:
    int getCount() const {
        return counter;
    }
    void increase() {
        std::lock_guard<std::mutex> lk(m);
        counter++;
    }
};

  1. Do I need to use std::lock_guard<std::mutex> lk(m); in getCount() method to make it thread-safe?

  2. What happen if there is only two threads: a reader thread and a writer thread then do I have to protect it at all? Because there is only one thread is modifying the variable so I think no lost update will happen.

  3. If there are multiple writer/reader for a shared primitive type variable (e.g. int) what disaster may happen if I only lock in write method but not read method? Will 8bits type make any difference compare to 64bits type?

  4. Is any primitive type are atomic by default? For example write to a char is always atomic? (I know this is true in Java but don't know about c++ and I am using llvm compiler on Mac if platform matters)

解决方案

Yes, unless you can guarantee that changes to the underlying variable counter are atomic, you need the mutex.

Classic example, say counter is a two-byte value that's incremented in (non-atomic) stages:

add 1 to lower byte
if lower byte is 0:
    add 1 to upper byte

and the initial value is 255.

If another thread comes in anywhere between the lower byte change and the upper byte change, it will read 0 rather than the correct 255 (pre-increment) or 256 (post-increment).

In terms of what data types are atomic, the latest C++ standard defines them in the <atomic> header.

If you don't have C++11 capabilities, then it's down to the implementation what types are atomic.

这篇关于多线程:我需要保护我的变量在只读方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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