在Go语言中 sync.Cond 代表条件变量,但它需要配置锁才能有用.
var m Mutex
c := NewCond(&m)
或 c := sync.NewCond(&sync.RWMutex{}) 之类. 它有三个函数: wait/signal/broadcast 望文知义,和Windows下的InitializeConditionVariable与WaitForSingleObject()之类, 及Linux下的pthread_cond_t等作用差不多.
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...
*/
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