Love My Love

Concurrency In Go Study

2020.08.11

Go 的并发很核心,理解不难,听懂也简单,但是用好它,很难!至少我现在觉得这东西好绕,当然这也说明我们没有学透彻,学明白,下面把学到的一些东西记录下来。算是二次理解。
Concurrency is go programing is a core tech, easy to understand but hard to use in best practices.

Reference:

https://www.kancloud.cn/mutouzhang/go/596822

Tips:

  1. Some words
  • Go的并发理念可以这样概括:为了简单起见,在可能的情况下使用通道,并且像免费资源一样处理goroutine(而不需要过多过早的考虑资源占用情况)。
  • 通道本质上比内存访问同步基元更具可组合性。
  • 将锁分散在各个结构中听起来像是一场噩梦。
  1. Ownership Transfer [USE CHANNEL]
    If some code section generate datas, you wanna use it in other section. => this means you wanna transfer this ownership of data to other section. => USE CHANNEL!
    Benefits: You can create buffer channels to implement memory queues with cheap resources.

  2. Guard Internal Struct [USE MUTEX]
    Don’t use channel but sync.Mutex!
    Benefits: Hide implementation details of locking section, reduce complexity to caller.
    Point: Try your best to limit the lock to a small area

type Counter struct {
    mu sync.Mutex value int

}
func(c *Counter) Increment()
{
    c.mu.Lock()
    defer c.mu.Unlock()
    c.value++

}
  1. Coordinate Multiple Pieces Of Logic [USE SELECT]
    如果你发现自己在努力了解并发代码的工作原理,为什么会发生死锁或竞争,并且你正在使用Mutex,这可能是你需要切换到通道的一个很好的信号。

TO BE CONTINUE…

发表评论