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

Multiple example with go routines:

Code 1:

package main

import (
    "fmt"
    "sync"
)

func even(ch chan int) {
    for {
        select {
            case no := <- ch:
                fmt.Println(no)
                ch <- -1
        }
    }
}

func odd(ch chan int) {
    for {
        select {
            case no := <- ch:
                fmt.Println(no)
                ch <- -1
        }
    }
}

func main() {
    wg := sync.WaitGroup{}
    m := sync.Mutex{}
    
    wg.Add(2)
    
    ch := make(chan int)
    
    go even(ch)
    go odd(ch)
    
    for i := 1; i <= 10; i++ {
        if (i & 1) == 0 {
            // Adding lock because wait until this number prints
            m.Lock()
            ch <- i
            <- ch
            m.Unlock()
        } else {
            m.Lock()
            ch <- i
            <- ch
            m.Unlock()
        }
    }
    wg.Done(); wg.Done()
    close(ch)
    
    return
}

Code 2:

package main

import (
    "fmt"
    "sync"
)

func print_odd(odd chan int) {
    for {
        select {
            case n := <- odd:
            fmt.Println("Odd: ", n)
        }
    }
}

func print_even(even chan int) {
    for {
        select {
            case n := <- even:
            fmt.Println("Even: ", n)
        }
    }
}

func main() {
    var wg sync.WaitGroup
    
    wg.Add(2)
    
    odd := make(chan int)
    even := make(chan int)
    
    go print_odd(odd)
    go print_even(even)
    
    for i := 0; i < 10; i++{
        if i % 2 == 0 {
            even <- i
        } else {
            odd <- i
        }
    }
    close(odd); close(even)
    wg.Done();
    wg.Done()
    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. Required fields are marked *

Contact Us