Commit f997ab7
committed
Complete fix for goroutine lifecycle race condition in Subscribe
Address comprehensive goroutine lifecycle management issue:
Problem:
The previous fix with buffered channel only prevented blocking, but didn't
prevent goroutine leaks. When the main function returns with an error or
due to context cancellation BEFORE the goroutine enters its main loop, the
goroutine would continue running indefinitely until the original context
expires (could be much later).
Complete Solution:
1. Added stop channel (chan struct{}) to signal goroutine termination
2. Goroutine checks stop channel during initialization (both error and success paths)
3. Goroutine checks stop channel as first case in main select loop
4. Main function closes stop channel when returning with error or ctx.Done()
5. Main function does NOT close stop on success - goroutine continues normally
This ensures:
- No goroutine leaks when Subscribe returns early with error
- No goroutine leaks when context is cancelled during initialization
- Clean resource cleanup via defer statements
- Goroutine runs normally when initialization succeeds
Verified with race detector running 3 consecutive times.1 parent 3fe25be commit f997ab7
1 file changed
Lines changed: 10 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
100 | 100 | | |
101 | 101 | | |
102 | 102 | | |
| 103 | + | |
103 | 104 | | |
104 | 105 | | |
105 | 106 | | |
| 107 | + | |
106 | 108 | | |
107 | 109 | | |
108 | 110 | | |
| |||
123 | 125 | | |
124 | 126 | | |
125 | 127 | | |
126 | | - | |
| 128 | + | |
127 | 129 | | |
128 | 130 | | |
129 | 131 | | |
130 | 132 | | |
131 | 133 | | |
132 | 134 | | |
133 | 135 | | |
134 | | - | |
| 136 | + | |
135 | 137 | | |
136 | 138 | | |
137 | 139 | | |
138 | 140 | | |
139 | 141 | | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
140 | 145 | | |
141 | 146 | | |
142 | 147 | | |
| |||
239 | 244 | | |
240 | 245 | | |
241 | 246 | | |
| 247 | + | |
242 | 248 | | |
243 | 249 | | |
| 250 | + | |
244 | 251 | | |
245 | 252 | | |
| 253 | + | |
246 | 254 | | |
247 | 255 | | |
248 | 256 | | |
| |||
0 commit comments