An error occurred while using WaitGroup. waitgroup is incorrect.
An error occurred while using WaitGroup.
Recently, when restructuring the server code I wrote earlier, I used WaitGroup improperly and encountered an error. record it.
Package mainimport ("fmt" "sync" "time") func main () {var wg sync. waitGroup wg. add (1) f1: = func () {time. sleep (time. second * 2) fmt. println ("func ()") wg. done ()} go f1 () go f1 () go f1 () wg. wait () fmt. println ("Done")}/* D: \ test \> go run testwg2.gofunc () func () panic: sync: negative WaitGroup countergoroutine 22 [running]: runtime. panic (0x4a56e0, 0xc082000250) c:/go/src/pkg/runtime/panic. c: 279 + 0x11fsync. (* WaitGroup ). add (0xc0820045e0, 0 xffffffffffffff) c:/go/src/pkg/sync/waitgroup. go: 64 + 0x9async. (* WaitGroup ). done (0xc0820045e0) c:/go/src/pkg/sync/waitgroup. go: 82 + 0x37main. func path 001 () D:/test/testwg2.go: 17 + 0xd2created by main. main D:/test/testwg2.go: 22 + 0x9a */
Error:Panic: sync: negative WaitGroup counter
Stackoverflow has a link to the problem.
Another error:
package mainimport ( "fmt" "sync" "time")func main() { var wg sync.WaitGroup wg.Add(10) f1 := func() { time.Sleep(time.Second * 2) fmt.Println("func()") wg.Done() } go f1() go f1() go f1() wg.Wait() fmt.Println("Done")}/*D:\test\>go run testwg2.gofunc()func()func()fatal error: all goroutines are asleep - deadlock!goroutine 16 [semacquire]:sync.runtime_Semacquire(0xc0820001bc) c:/go/src/pkg/runtime/sema.goc:199 +0x37sync.(*WaitGroup).Wait(0xc0820045e0) c:/go/src/pkg/sync/waitgroup.go:129 +0x152main.main() D:/test/testwg2.go:24 +0xaagoroutine 19 [finalizer wait]:runtime.park(0x414db0, 0x55ec80, 0x55d689) c:/go/src/pkg/runtime/proc.c:1369 +0xacruntime.parkunlock(0x55ec80, 0x55d689) c:/go/src/pkg/runtime/proc.c:1385 +0x42runfinq() c:/go/src/pkg/runtime/mgc0.c:2644 +0xddruntime.goexit() c:/go/src/pkg/runtime/proc.c:1445exit status 2*/
In fact, these errors were mainly handled separately by wg add and done for some reasons. While
Because a lot of processing is interspersed in the middle, done causes wg negative numbers, such as Example 1 or add
And done cause deadlock.
In the future, we should pay attention to the need to reduce the intermediate processing as much as possible, so as to simplify the corresponding processing.
However, the reconstruction of the server has been quite cool recently. After much code cleaning and sorting out the process.
The code looks a lot better. However, there is still a long way to go.
BLOG: blog.csdn.net/xcl168