Menu Close

Go – Program to print natural numbers using two go routines in go.

We are going to write a program to print natural numbers using two go routines in go. One go routine will be responsible to print odd numbers and another go routine will be responsible to print even numbers.

Algorithm:

  • Create two go routines i.e odd and even from main with bool type channel
  • In odd / even function, Add channel to receive value next to for loop
  • In odd / even function, Add channel to send value at the end of for loop

Example with code:

package main

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

func even(ch chan int, wg *sync.WaitGroup) {

	for {
		select {
		case no := <-ch:
			if no%2 == 0 {
				fmt.Println(no)
			} else {
				ch <- no
			}
		}
	}
}

func odd(ch chan int, wg *sync.WaitGroup) {

	for {
		select {
		case no := <-ch:
			if no%2 != 0 {
				fmt.Println(no)
			} else {
				ch <- no
			}
		}
	}
}

func main() {
	var wg sync.WaitGroup
	wg.Add(2)

	ch := make(chan int)

	go odd(ch, &wg)
	go even(ch, &wg)

	for i := 1; i <= 5; i++ {
		ch <- i
		time.Sleep(time.Second * 1)
	}

	close(ch)

	wg.Done()
	wg.Done()

	wg.Wait()
}

Code example 2:

//Program a program to print natural number.

package main

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

func odd(ch chan bool, wg *sync.WaitGroup) {

  for i := 1; ; i = i + 2 {

    <- ch

    time.Sleep(1*time.Second)

    fmt.Println(i)

    ch <- true

  }

  wg.Done()
}

func even(ch chan bool, wg *sync.WaitGroup) {

  for i := 2; ; i = i + 2{

    <- ch

    time.Sleep(1*time.Second)

    fmt.Println(i)

   ch <- true

  }

 wg.Done()

}

func main(){

  var wg sync.WaitGroup

  ch := make(chan bool)

  wg.Add(2)

  go even(ch, &wg)

  go odd(ch, &wg)

  ch <- true

  wg.Wait()

 }

Output:

1
2
3
4
5
..
..
..

To learn more about technical stuff, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, golang program

Leave a Reply

Your email address will not be published.

Contact Us