duanque3125 2019-03-04 12:08
浏览 41
已采纳

为什么sync.Mutex存在?

Why sync.Mutex exists while we have sync.RWMutex? I can lock/unlock rw mutex. What is the main difference between them?

  • 写回答

2条回答 默认 最新

  • dongqishun6409 2019-03-04 12:19
    关注

    It's true that you could use a sync.RWMutex whenever you need a sync.Mutex.

    I think both exist because there are a lot of cases when a sync.Mutex is enough (you don't need read and write level locking), and the implementation of sync.Mutex is simpler: requires much less memory and is most likely faster.

    sync.Mutex is just 8 bytes:

    type Mutex struct {
        state int32
        sema  uint32
    }
    

    While sync.RWMutex is 8 + 16 = 24 bytes (it includes a sync.Mutex):

    type RWMutex struct {
        w           Mutex  // held if there are pending writers
        writerSem   uint32 // semaphore for writers to wait for completing readers
        readerSem   uint32 // semaphore for readers to wait for completing writers
        readerCount int32  // number of pending readers
        readerWait  int32  // number of departing readers
    }
    

    Yes, you could say 8 or 24 bytes should not matter. And it doesn't as long as you only have a few mutexes.

    But it's not uncommon to put the mutex into the struct it's ought to protect (either embed or a regular, named field). Now if you have a slice of these struct values, maybe even thousands of them, then yes, it will make a noticeable difference.

    Also, if you just need a mutex, sync.Mutex gives you less chance of misusing it (you can't accidentally call RLock() because it doesn't have that method).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败