dtpn60029 2017-01-03 12:15
浏览 92
已采纳

Golang Mutex锁定特定变量/映射

I'm a little confused on how mutex's work in Golang, even though I've used them before.

Here are my questions:

  1. What exactly does a mutex lock? (How) Do you use it to lock a specific variable only?

  2. Should I use channels instead of a mutex?

  3. Is there a difference between a mutex and a locker?

I'm developing a highly concurrent website with golang, and I need to manage each person's wallet at different times and I am trying to avoid any races in my program. For example, if my program wants to add 500 credits to a user, it will read the current balance for the user (from firebase) and add 500 then update the value. But if it does this twice for some reason, there may be an incorrect change to the user's wallet.

  • 写回答

3条回答 默认 最新

  • dqv84329 2017-01-03 15:46
    关注

    What is a Mutex?

    In general, a "mutual exclusion" construct (or mutex) helps with concurrency control. Languages that define mutexes let programmers define a critical section of code that can only be entered by a single thread of execution. Here is a simple example of using mutexes in Go. Here is a bit more detailed example of using mutexes.

    Mutex or Channel?

    When deciding whether to use a mutex or channel based design in your Go app, the choices aren't always terribly clear. This wiki article from the Go github repo has the following advice:

    Channel: passing ownership of data, distributing units of work, communicating async results

    Mutex: caches, state

    Mutex or sync.Locker?

    As @JimB pointed out, the sync.Mutex type in Go satisfies the sync.Locker interface type. Notice how sync.Mutex has Lock() and Unlock() methods? So to Go, a sync.Mutex is a sync.Locker.

    For more help with Go interfaces, check out this great blog post.

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

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势