confusion about using make()

0 views
Skip to first unread message

ish

unread,
Apr 13, 2010, 3:13:11 PM4/13/10
to golang-nuts
The follwoing code does SIGSEGV, any insight will be appreciated.
-ishwar
------
package main

import "fmt"

var mtx chan int
var sem []chan int

func sink() {
val := <-mtx
for i := 0; i < 10; i++ {
val = <-sem[i]
}
fmt.Println("V: ", val)
}

func source() {
mtx <- 1
for i := 0; i < 10; i++ {
sem[i] <- i
}
}

func main() {
mtx = make(chan int)
sem = make([]chan int, 10)
go sink()
go source()
fmt.Println("All done!")
}
---

chris dollin

unread,
Apr 13, 2010, 3:17:45 PM4/13/10
to ish, golang-nuts
On 13 April 2010 20:13, ish <ishwar...@gmail.com> wrote:

  sem = make([]chan int, 10)

sem is a slice containg 10 nils. If you try and communicate
through them, BOOM.

Chris

--
Chris "there's always a BOOM tomorrow" Dollin

Andrew Gerrand

unread,
Apr 14, 2010, 2:45:44 AM4/14/10
to ish, golang-nuts
You need to make the channels in sem. You only make'd the slice.

See below.

On 14 April 2010 05:13, ish <ishwar...@gmail.com> wrote:
> The follwoing code does SIGSEGV, any insight will be appreciated.
> -ishwar
> ------
> package main
>
> import "fmt"
>
> var mtx chan int
> var sem []chan int
>
> func sink() {
>    val := <-mtx
>    for i := 0; i < 10; i++ {
>        val = <-sem[i]
>    }
>    fmt.Println("V: ", val)
> }
>
> func source() {
>     mtx <- 1
>     for i := 0; i < 10; i++ {
>           sem[i] <- i
>     }
> }
>
> func main() {
>   mtx = make(chan int)
>   sem = make([]chan int, 10)
for i := 0; i < 10; i++ {

sem[i] = make(chan int)

Reply all
Reply to author
Forward
0 new messages