Golang 游戏leaf系列(六) Go模块

在Golang 游戏leaf系列(一) 概述与示例(下文简称系列一)中,提到过Go模块用于创建能够被 Leaf 管理的 goroutine。Go模块是对golang中go提供一些额外功能。Go提供回调功能,LinearContext提供顺序调用功能。善用 goroutine 能够充分利用多核资源,Leaf 提供的 Go 机制解决了原生 goroutine 存在的一些问题:

  • 能够恢复 goroutine 运行过程中的错误
  • 游戏服务器会等待所有 goroutine 执行结束后才关闭
  • 非常方便的获取 goroutine 执行的结果数据
  • 在一些特殊场合保证 goroutine 按创建顺序执行

我们来看一个例子(可以在 LeafServer 的模块的 OnInit 方法中测试):

log.Debug("1")

// 定义变量 res 接收结果
var res string

skeleton.Go(func() {
    // 这里使用 Sleep 来模拟一个很慢的操作
    time.Sleep(1 * time.Second)

    // 假定得到结果
    res = "3"
}, func() {
    log.Debug(res)
})

log.Debug("2")

//上面代码执行结果如下:
2015/08/27 20:37:17 [debug  ] 1
2015/08/27 20:37:17 [debug  ] 2
2015/08/27 20:37:18 [debug  ] 3

这里的 Go 方法接收 2 个函数作为参数,第一个函数会被放置在一个新创建的 goroutine 中执行,在其执行完成之后,第二个函数会在当前 goroutine 中被执行。由此,我们可以看到变量 res 同一时刻总是只被一个 goroutine 访问,这就避免了同步机制的使用。Go 的设计使得 CPU 得到充分利用,避免操作阻塞当前 goroutine,同时又无需为共享资源同步而忧心。

一、go/example_test.go里面的示例一
func Example() {
    d := g.New(10)

    // go 1
    var res int
    d.Go(func() {
        fmt.Println("1 + 1 = ?")
        res = 1 + 1
    }, func() {
        fmt.Println(res)
    })

    d.Cb(<-d.ChanCb)

    // go 2
    d.Go(func() {
        fmt.Print("My name is ")
    }, func() {
        fmt.Println("Leaf")
    })

    d.Close()

    // Output:
    // 1 + 1 = ?
    // 2
    // My name is Leaf
}

这里主动调用了d.Cb(<-d.ChanCb),把这个回调取出来了。实际上,在skeleton.Run里会自己取这个通道

// leaf\module\skeleton.go
func (s *Skeleton) Run(closeSig chan bool) {
    for {
        select {
        case <-closeSig:
            s.commandServer.Close()
            s.server.Close()
            for !s.g.Idle() || !s.client.Idle() {
                s.g.Close()
                s.client.Close()
            }
            return
        case ri := <-s.client.ChanAsynRet:
            s.client.Cb(ri)

        // 等待来自通道的数据
        case ci := <-s.server.ChanCall:
            s.server.Exec(ci)

        case ci := <-s.commandServer.ChanCall:
            s.commandServer.Exec(ci)
        case cb := <-s.g.ChanCb:
            s.g.Cb(cb)
        case t := <-s.dispatcher.ChanTimer:
            t.Cb()
        }
    }
}

看一下源码:

func New(l int) *Go {
    g := new(Go)
    g.ChanCb = make(chan func(), l)
    return g
}

func (g *Go) Go(f func(), cb func()) {
    g.pendingGo++

    go func() {
        defer func() {
            g.ChanCb <- cb
            if r := recover(); r != nil {
                if conf.LenStackBuf > 0 {
                    buf := make([]byte, conf.LenStackBuf)
                    l := runtime.Stack(buf, false)
                    log.Error("%v: %s", r, buf[:l])
                } else {
                    log.Error("%v", r)
                }
            }
        }()

        f()
    }()
}

func (g *Go) Cb(cb func()) {
    defer func() {
        g.pendingGo--
        if r := recover(); r != nil {
            if conf.LenStackBuf > 0 {
                buf := make([]byte, conf.LenStackBuf)
                l := runtime.Stack(buf, false)
                log.Error("%v: %s", r, buf[:l])
            } else {
                log.Error("%v", r)
            }
        }
    }()

    if cb != nil {
        cb()
    }
}

New方法,会生成指定缓冲长度的ChanCb。然后调用Go方法就是先执行第一个func,然后把第二个放到Cb里。现在手动造一个例子:

    d.Go(func() {
        fmt.Println("1 + 1 = ?")
    }, func() {
        fmt.Println("2")
    })

    d.Go(func() {
        fmt.Println("1 + 2 = ?")
    }, func() {
        fmt.Println("3")
    })
    //time.Sleep(time.Second)
    d.Cb(<-d.ChanCb)
    fmt.Println("len",len(d.ChanCb),"cap",cap(d.ChanCb))
    d.Cb(<-d.ChanCb)
    fmt.Println("end")
----------------------
1 + 2 = ?
3
len 0 cap 10
1 + 1 = ?
2
end

这里解释一下,d.Go根据源码来看,实际也是调用了一个协程。然后上面两次d.Go并不能保证先后顺序。目前的输出结果是1+2那个先执行了,把3写入d.ChanCb,然后把3读出来,继续读时,d.ChanCb里没有东西,阻塞了。然后1+1那个协程启动了,最后又读到了2。

现在把time.Sleep(time.Second)的注释解开,会是啥结果呢

1 + 2 = ?
1 + 1 = ?
3
len 1 cap 10
2
end

这里执行到time.Sleep睡着了,上面两个d.Go仍然是不确定顺序的,但是会各自的function先执行掉,然后陆续把cb写入d.ChanCb。看这次输出,1+2先写进去的。所以最后执行d.Cb时,就把3先读出来了。然后d.ChanCb的长度为1,说明还有一个,就是输出2了。

另外,就是close时会判断g.pendingGo

func (g *Go) Close() {
    for g.pendingGo > 0 {
        g.Cb(<-g.ChanCb)
    }
}

func (g *Go) Idle() bool {
    return g.pendingGo == 0
}
二、go/example_test.go里面的示例二
func ExampleLinearContext() {
    d := g.New(10)

    // parallel
    d.Go(func() {
        time.Sleep(time.Second / 2)
        fmt.Println("1")
    }, nil)
    d.Go(func() {
        fmt.Println("2")
    }, nil)

    d.Cb(<-d.ChanCb)
    d.Cb(<-d.ChanCb)

    // linear
    c := d.NewLinearContext()
    c.Go(func() {
        time.Sleep(time.Second / 2)
        fmt.Println("1")
    }, nil)
    c.Go(func() {
        fmt.Println("2")
    }, nil)

    d.Close()

    // Output:
    // 2
    // 1
    // 1
    // 2
}

这个例子的意思很明显,NewLinearContext这种方式,即使先调用的慢了半秒,它还是会先执行完。

type LinearGo struct {
    f  func()
    cb func()
}

type LinearContext struct {
    g              *Go
    linearGo       *list.List
    mutexLinearGo  sync.Mutex
    mutexExecution sync.Mutex
}

func (g *Go) NewLinearContext() *LinearContext {
    c := new(LinearContext)
    c.g = g
    c.linearGo = list.New()
    return c
}

func (c *LinearContext) Go(f func(), cb func()) {
    c.g.pendingGo++

    c.mutexLinearGo.Lock()
    c.linearGo.PushBack(&LinearGo{f: f, cb: cb})
    c.mutexLinearGo.Unlock()

    go func() {
        c.mutexExecution.Lock()
        defer c.mutexExecution.Unlock()

        c.mutexLinearGo.Lock()
        e := c.linearGo.Remove(c.linearGo.Front()).(*LinearGo)
        c.mutexLinearGo.Unlock()

        defer func() {
            c.g.ChanCb <- e.cb
            if r := recover(); r != nil {
                if conf.LenStackBuf > 0 {
                    buf := make([]byte, conf.LenStackBuf)
                    l := runtime.Stack(buf, false)
                    log.Error("%v: %s", r, buf[:l])
                } else {
                    log.Error("%v", r)
                }
            }
        }()

        e.f()
    }()
}

这里先是用了一个list,加入的时候用mutexLinearGo锁了,都加到最后。然后新开协程去处理,读的时候从最前面开始读,也要用mutexLinearGo锁。执行的时候,也要上锁mutexExecution,确保f()执行完并且写入g.ChanCb回调,这个mutexExecution锁才会解除。现在可以改造一个带回调的例子:

func Example3(){
    d := g.New(10)
    c := d.NewLinearContext()
    c.Go(func() {
        time.Sleep(time.Second / 2)
        fmt.Println("1+1=?")
    }, func() {
        fmt.Println("2")
    })

    c.Go(func() {
        fmt.Println("1+2=?")
    }, func() {
        fmt.Println("3")
    })
    d.Cb(<-d.ChanCb)
    fmt.Println("len",len(d.ChanCb),"cap",cap(d.ChanCb))
    d.Cb(<-d.ChanCb)
    fmt.Println("end")
}
------------
1+1=?
1+2=?
2
len 1 cap 10
3
end

结果说明,确实是2先被写入了d.ChanCb。

你可能感兴趣的:(Golang 游戏leaf系列(六) Go模块)