前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang语言情怀-第36期 Go 语言设计模式 条件变量

Golang语言情怀-第36期 Go 语言设计模式 条件变量

作者头像
李海彬
发布2021-03-09 10:53:44
3480
发布2021-03-09 10:53:44
举报
文章被收录于专栏:Golang语言社区Golang语言社区

在Go语言中 sync.Cond 代表条件变量,但它需要配置锁才能有用.

var m Mutex

c := NewCond(&m)

或 c := sync.NewCond(&sync.RWMutex{}) 之类. 它有三个函数: wait/signal/broadcast 望文知义,和Windows下的InitializeConditionVariable与WaitForSingleObject()之类, 及Linux下的pthread_cond_t等作用差不多.

代码语言:javascript
复制
package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

func main() {

    runtime.GOMAXPROCS(4)

    test333()
}

func testCond() {

    c := sync.NewCond(&sync.Mutex{})
    condition := false

    go func() {
        time.Sleep(time.Second * 1)
        c.L.Lock()
        fmt.Println("[1] 变更condition状态,并发出变更通知.")
        condition = true
        c.Signal() //c.Broadcast()
        fmt.Println("[1] 继续后续处理.")
        c.L.Unlock()

    }()

    c.L.Lock()
    fmt.Println("[2] condition..........1")
    for !condition {
        fmt.Println("[2] condition..........2")
        //等待Cond消息通知
        c.Wait()
        fmt.Println("[2] condition..........3")
    }
    fmt.Println("[2] condition..........4")
    c.L.Unlock()

    fmt.Println("main end...")
}

/*

testCond()运行结果:

[2] condition..........1
[2] condition..........2
[1] 变更condition状态,并发出变更通知.
[1] 继续后续处理.
[2] condition..........3
[2] condition..........4
main end...


*/
代码语言:javascript
复制
func init() {
    LollipopGo.Run()
    impl.IMsg = new(models.Game)
    CacheGame = cache2go.Cache("GameCache")
    M = concurrent.NewConcurrentMap()
    conf.InitConfig()
    InitProxyNet()
}

// 连接proxy服务器
func InitProxyNet() {
    proxyURL := req.AddParamsToGetReq(g.Ws, conf.ServerConfig().GetProxyUrlList(), map[string]string{"data": "{ID:1}"})
    glog.Infof("connect to proxy addr:%s\n", proxyURL)
    conn, err := websocket.Dial(proxyURL, "", "test://golang/")
    if err != nil {
        glog.Errorln("err:", err.Error())
        return
    }
    ConnXZ = conn
    // 保存内部到配置模块连接
    tables.SetConfigConn(ConnXZ)
    // bs
    bigsmall.SetConn(conn)
    //--------------------------------------------------------------------------
    // 发送保存链接
    data := Proto_Proxy.G2Proxy_ConnData{
        Protocol:  twlib_proto.GameDataProto,
        Protocol2: Proto_Proxy.G2Proxy_ConnDataProto,
        ServerID:  util.MD5_LollipopGO(strconv.Itoa(twlib_server.GameServerId)),
    }
    impl.PlayerSendToServer(conn, data)
    go GameServerReceive(ConnXZ)
}

func GameServerReceive(ws *websocket.Conn) {
    for {
        var content string
        err := websocket.Message.Receive(ws, &content)
        if err != nil {
            continue
        }
        //glog.Info(strings.Trim("", "\""))
        //glog.Info(content)
        content = strings.Replace(content, "\"", "", -1)
        contentstr, errr := base64Decode([]byte(content))
        if errr != nil {
            glog.Errorln(errr)
            continue
        }
        //glog.Info("收到数据:", string(contentstr))
        go SyncMessageFun(string(contentstr))
    }
}

参考资料:

Go语言设计模式

https://studygolang.com/articles/5956

设计模式

https://blog.csdn.net/weixin_34210740/article/details/88061887

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-02-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言情怀 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档