Golang 并行运算以及time/sleep.go

Golang 并行运算以及time/sleep.go_第1张图片

今天大概阅读了一下Golang的并行运算,以下简要概括并行运算

go func()  // 可以启动一个协程

可以同时运行多个协程,协程之间通讯使用channel(通道)来进行协程间通信

channel的定义如下

c := chan string

意味着这是一个string类型的通道

channel可以理解为一个队列,先进者先出,但是它只能占有一个元素的位置,我们可以义如下方法添加/读取元素,<- 是一个运算符

c <- "hello"  //把"hello"加入到c通道中
msg := <- c // 将c中的"hello"取出到msg里

在并行运算时我们可能需要从多个通道读取消息,此时我们用到

for{
  select{
    case msg1 := channel_1:
      fmt.Println(msg1)
    case msg2 := channel_2:
      fmt.Println(msg2)
  }
}

此时如果channel_1和channel_2两个通道都一直没有消息,那么该协程将会被阻塞在select语句,直到channel_1或者channel_2有消息为止

那如何解决阻塞问题呢?

我们需要在select中再添加一种情况,代码如下

for{
  select{
    case msg1 := <- channel_1:
      fmt.Println(msg1)
    case msg2 := <- channel_2:
      fmt.Println(msg2)
    case msg3 := <- time.After(time.second*5):
      fmt.Println("get message time out, check again...")
  }
}

意思是如果在select中停留5秒钟还没有收到channel1和channel2的消息,那么time.After(time.second*5)就会返回一个搭载了当前时间的一个通道,此时select就能正确响应了

看到这里博主就有点呆了

不太理解time.After()这是一个什么东西,居然能够这么神奇地等待5秒钟就可以返回通道
于是无奈之下只能瞅一瞅time.After的源代码,因为是第一天学Go语言所以很多东西还是不太懂,只能看懂大概的

大概的情况是这样的:

// 函数原型
// 文件:../time/sleep.go
func After(d Duration) <-chan Time {
    return NewTimer(d).C
}
func NewTimer(d Duration) *Timer {
    c := make(chan Time, 1)
    t := &Timer{
        C: c,
        r: runtimeTimer{
            when: when(d),
            f:    sendTime,
            arg:  c,
        },
    }
    startTimer(&t.r)
    return t
}

type runtimeTimer struct {
    tb uintptr
    i  int

    when   int64
    period int64
    f      func(interface{}, uintptr) // NOTE: must not be closure
    arg    interface{}
    seq    uintptr
}

以上是涉及到time.After()的函数原型,time.After()执行的步骤是这样子的:

  1. After()里直接调用NewTimer(),在NewTimer里创建一个Timer对象并将指针储存在t里,通过startTimer(&t.r)传入runtimeTimer来创建一个协程,这个协程会在指定的时间(5秒)后将一个Time对象送入t.C这个通道中。(runtimeTimer这里不深究)
  2. 将包含C(channel)和r(runtimeTimer)的t返回到After()函数的NewTimer(d)中
  3. After函数返回NewTimer(d).C,即After()最终返回的通道
  4. select此时已经过了5秒钟,并检测到了这个携带Time对象(当前时间)的通道的返回,便输出“get message time out, check again...”

本文待更新....初学Golang,大佬路过请指正!

你可能感兴趣的:(Golang 并行运算以及time/sleep.go)