Deadlock -> kondisi dimana go routine saling tunggu -> alhasil tidak ada go routine yang berjalan.
Contoh Kasus #1
Jika channel in (pengirim) di inisisasi terlebih dahulu dan channel out (penerima) di inisiasi setelah channel in -> deadlock -> karena belum ada penerimanya.
Channel in dan channel out harus berjalan bersama -> caranya salah satu di inisiasi terlebih dahulu dan yang pertama di inisiasi dimasukkan ke dalam go routine.
Program #1
packagemainimport"fmt"funcmain() { ch :=make(chanint)// channel in (pengirim) ch <-1// channel out (penerima)gofunc() { result :=<- ch fmt.Println(result) }()}
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/uv1yQwKDgN.go:7 +0x37
exit status 2
packagemainimport"fmt"funcmain() { ch :=make(chanint)// channel out (penerima)gofunc() { result :=<- ch fmt.Println(result) }()// channel in (pengirim) ch <-1}
1
packagemainimport"fmt"funcmain() { ch :=make(chanint)// channel in (pengirim)gofunc() { ch <-1 }()// channel out (penerima) result :=<- ch fmt.Println(result)}
1
Program #2
packagemainimport"fmt"funcf(value chanint) { result :=100+<- value fmt.Printf("%d ", result)}funcmain() { fmt.Println("Start") value :=make(chanint)for i :=0; i <10; i++ {// channel in (pengirim) value <- i// channel out (penerima)gof(value) } fmt.Println("\nEnd")close(value)}
Start
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
D:/go-server/main.go:15 +0x9e
exit status 2
packagemainimport"fmt"funcf(value chanint) { result :=100+<- value fmt.Printf("%d ", result)}funcmain() { fmt.Println("Start") value :=make(chanint)for i :=0; i <10; i++ {//channel out (penerima)gof(value)// channel in (pengirim) value <- i } fmt.Println("\nEnd")close(value)}
Start
100 101 102 103 104 105 106 107 108 109
End
packagemainimport"fmt"funcf(value chanint) { result :=100+<- value fmt.Printf("%d ", result)}funcmain() { fmt.Println("Start") value :=make(chanint)for i :=0; i <10; i++ {// channel in (pengirim)gofunc() { value <- i }()//channel out (penerima)f(value) } fmt.Println("\nEnd")close(value)}
Start
100 101 102 103 104 105 106 107 108 109
End
Program #3 deadlock jika channel tidak di close
packagemainimport ("fmt")funcmain() { ch :=make(chanint)gofunc() {for i :=0; i <5; i++ {// channel in ch <- i }// channel must be close// if not will be deadlockclose(ch) }()// channel outfor v :=range ch { fmt.Println(v) }}