简体   繁体   中英

golang chanel not working with sync.WaitGroup

my code



package main

import (
   "fmt"
   "sync"
)

func other(c chan int, wg *sync.WaitGroup) {
   c <- 455
   wg.Done()
}

func addInt(c chan int, d int, wg *sync.WaitGroup) {
   c <- d
   wg.Done()
}
func main() {

   var wg sync.WaitGroup
   myChanel := make(chan int)

   wg.Add(2)

   go addInt(myChanel, 5, &wg)
   go other(myChanel, &wg)

   wg.Wait()

   c := 0


   for v := range myChanel {
       if c == 1 {

           close(myChanel)
       }
       fmt.Println(v)
       c++

   }

}


I am learning golang looking at mines, but it is true I got such an error. I looked at other sources. I couldn't reach a healthy solution. I tried shutdown (Chanel) again.

error output

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [semacquire]:
sync.runtime_Semacquire(0xc0000140f8)
        /usr/lib/go-1.13/src/runtime/sema.go:56 +0x42
sync.(*WaitGroup).Wait(0xc0000140f0)
        /usr/lib/go-1.13/src/sync/waitgroup.go:130 +0x64
main.main()
        /home/zeus/go/src/github.com/awesomeProject/pool.go:27 +0xe4

goroutine 6 [chan send]:
main.addInt(0xc000016120, 0x5, 0xc0000140f0)
        /home/zeus/go/src/github.com/awesomeProject/pool.go:14 +0x3f
created by main.main
        /home/zeus/go/src/github.com/awesomeProject/pool.go:24 +0xaa

goroutine 7 [chan send]:
main.other(0xc000016120, 0xc0000140f0)
        /home/zeus/go/src/github.com/awesomeProject/pool.go:9 +0x37
created by main.main
        /home/zeus/go/src/github.com/awesomeProject/pool.go:25 +0xd6
exit status 2

You have an unbuffered channel, which means you can't send on it until there is something waiting to receive.

So when you do:

wg.Wait()

before you do

for v := range myChanel

you'll never be able to get to the receiver.

I've never needed to use a waitgroup when using unbuffered channels anyways, in my experience you only need them when doing concurrent stuff without channels. You can just do it like this: https://play.golang.org/p/-SUuXGlFd1E

ı solved it

run it

package main

import (
    "fmt"
    "sync"
    "time"
)

func other(c chan int, wg *sync.WaitGroup) {
    time.Sleep(time.Second*1)
    c <- 455
    wg.Done()
}

func addInt(c chan int, d int, wg *sync.WaitGroup) {
    c <- d
    wg.Done()
}
func main() {

    var wg sync.WaitGroup
    myChanel := make(chan int)

    wg.Add(2)

    go addInt(myChanel, 5, &wg)
    go other(myChanel, &wg)

    go func() {
        wg.Wait()
        close(myChanel)
    }()

    for v := range myChanel {
        fmt.Println(v)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM