@@ -52,9 +52,8 @@ type Conn struct {
52
52
br * bufio.Reader
53
53
bw * bufio.Writer
54
54
55
- readTimeout chan context.Context
56
- writeTimeout chan context.Context
57
- timeoutLoopDone chan struct {}
55
+ readTimeoutCloser atomic.Value
56
+ writeTimeoutCloser atomic.Value
58
57
59
58
// Read state.
60
59
readMu * mu
@@ -104,10 +103,6 @@ func newConn(cfg connConfig) *Conn {
104
103
br : cfg .br ,
105
104
bw : cfg .bw ,
106
105
107
- readTimeout : make (chan context.Context ),
108
- writeTimeout : make (chan context.Context ),
109
- timeoutLoopDone : make (chan struct {}),
110
-
111
106
closed : make (chan struct {}),
112
107
activePings : make (map [string ]chan <- struct {}),
113
108
}
@@ -133,8 +128,6 @@ func newConn(cfg connConfig) *Conn {
133
128
c .close ()
134
129
})
135
130
136
- go c .timeoutLoop ()
137
-
138
131
return c
139
132
}
140
133
@@ -164,26 +157,42 @@ func (c *Conn) close() error {
164
157
return err
165
158
}
166
159
167
- func (c * Conn ) timeoutLoop () {
168
- defer close (c .timeoutLoopDone )
160
+ func (c * Conn ) setupWriteTimeout (ctx context.Context ) {
161
+ hammerTime := context .AfterFunc (ctx , func () {
162
+ c .close ()
163
+ })
169
164
170
- readCtx := context .Background ()
171
- writeCtx := context .Background ()
165
+ if closer := c .writeTimeoutCloser .Swap (hammerTime ); closer != nil {
166
+ if fn , ok := closer .(func () bool ); ok {
167
+ fn ()
168
+ }
169
+ }
170
+ }
172
171
173
- for {
174
- select {
175
- case <- c .closed :
176
- return
177
-
178
- case writeCtx = <- c .writeTimeout :
179
- case readCtx = <- c .readTimeout :
180
-
181
- case <- readCtx .Done ():
182
- c .close ()
183
- return
184
- case <- writeCtx .Done ():
185
- c .close ()
186
- return
172
+ func (c * Conn ) clearWriteTimeout () {
173
+ if closer := c .writeTimeoutCloser .Load (); closer != nil {
174
+ if fn , ok := closer .(func () bool ); ok {
175
+ fn ()
176
+ }
177
+ }
178
+ }
179
+
180
+ func (c * Conn ) setupReadTimeout (ctx context.Context ) {
181
+ hammerTime := context .AfterFunc (ctx , func () {
182
+ defer c .close ()
183
+ })
184
+
185
+ if closer := c .readTimeoutCloser .Swap (hammerTime ); closer != nil {
186
+ if fn , ok := closer .(func () bool ); ok {
187
+ fn ()
188
+ }
189
+ }
190
+ }
191
+
192
+ func (c * Conn ) clearReadTimeout () {
193
+ if closer := c .readTimeoutCloser .Load (); closer != nil {
194
+ if fn , ok := closer .(func () bool ); ok {
195
+ fn ()
187
196
}
188
197
}
189
198
}
0 commit comments