dongqianwei6664 2015-08-12 19:00
浏览 41
已采纳

如何在没有比赛的情况下延长股票行情的持续时间?

I'm trying to implement a keepAlive mechanism. The issue is that I don't know how to replace the keep alive ticker ( conn.keepAlive) without a race because keepAlive() method always reads from the ticker.

//errors not handled for brevity
const interval = 10 * time.Second

type conn struct {
    keepAlive time.Ticker
    conn      net.Conn
    mux       sync.Mutex
}

// replace replaces the underlying connection
func (cn conn) replace(newcn net.Conn) {
    cn.mux.Lock()
    cn.conn = newcn
    // reset the ticker
    cn.keepAlive.Stop
    cn.keepAlive = time.NewTicker(interval)
    cn.mux.Unlock()
}

func (cn conn) keepAlive() {
    for {
        <-cn.keepAlive.C
        cn.mux.Lock()
        cn.conn.Write([]byte("ping"))
        var msg []byte
        cn.conn.Read(msg)
        if string(msg) != "pong" {
            // do some mean stuff
        }
        cn.keepAlive = time.NewTicker(interval)
        cn.mux.Unlock()
    }
}
  • 写回答

2条回答 默认 最新

  • duanrang3357 2015-08-12 20:44
    关注

    One way to implement this much more succinctly, is by using a channel as the synchronization mechanism, instead of the mutex:

    type conn struct {
        sync.Mutex
        conn        net.Conn
        replaceConn chan net.Conn
    }
    
    // replace replaces the underlying connection
    func (cn *conn) replace(newcn net.Conn) {
        cn.replaceConn <- newcn
    }
    
    func (cn *conn) keepAlive() {
        t := time.NewTicker(interval)
        msg := make([]byte, 10)
    
        for {
            select {
            case <-t.C:
            case newConn := <-cn.replaceConn:
                cn.Lock()
                cn.conn = newConn
                cn.Unlock()
                continue
            }
    
            cn.Lock()
            _ = msg
            // do keepalive
            cn.Unlock()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题