Thursday, April 18, 2024
HomeGolangFundamental channel instance which isn't working - Technical Dialogue

Fundamental channel instance which isn’t working – Technical Dialogue


func primary() {
    c := make(chan int, 1)
    go ship(c)
    go obtain(c)
}

// ship channel
func ship(c chan<- int) {
    for i := 0; i < 10; i++ {
        c <- i
    }
    //shut(c)               //  dont need to do it , this isn't logical.
}

// obtain channel
func obtain(c <-chan int) {
    for v := vary c {                                                                              // that is an infinite loop that may maintain working as soon as the channel may have content material.
        fmt.Println("Obtained from the channel:", v)                    this loop will cease solely in case the channel will get closed. 
    }
}

what’s the idea right here that i’m lacking , why is it not exhibiting any output ?
when i add the “shut(c)” it’s working, however i don’t wish to shut any channels – need them to be open
for additional use.

thanks upfront. @)
#channels #go channels #plz add hash tags – i believe it’ll assist round right here.

Hello @edgarlip,

After spawning the 2 goroutines, primary has nothing extra to do and exits. When it exits, the method exits and all goroutines cease forcefully. obtain() has no probability to print something.

Listed below are just a few methods to keep away from this:

  1. The fast repair: name obtain() instantly (that’s, take away the go key phrase), in order that it runs in the principle movement.
  2. For extra complicated eventualities: add all goroutines to a WaitGroup and have primary watch for the group to finish.
  3. The soiled hack: on the finish of primary, add a name that blocks without end, like choose{}. Exit the app with Ctrl-C.

Hello @christophberger
thanks for the short replay !
based mostly on you remark i’ve got here up with this code :

func primary() {
	c := make(chan int, 12)
	var wg sync.WaitGroup
	wg.Add(2)
	go ship(c, &wg)
	go obtain(c, &wg)
	wg.Wait()
}

// ship channel
func ship(c chan int, wg *sync.WaitGroup) {
	for i := 0; i < 10; i++ {
		fmt.Println("inserting stuff to channel c ", i)
		c <- i
	}
	fmt.Println("ship func completed")
	shut(c)
	wg.Achieved()
}

// obtain channel
func obtain(c chan int, wg *sync.WaitGroup) {
	for v := vary c {
		fmt.Println("the worth acquired from the channel:", v)
	}
	fmt.Println("obtain func completed")
	wg.Achieved()
}

however nonetheless as u can see within the ship operate i see that the shut() is a should ?

Sure, that you must shut the channel as a result of the vary loop reads from the channel till it’s closed.

In different phrases, closing a channel is like sending a sign to the vary operator in order that it is aware of that no extra knowledge might be coming by the channel.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments