DEV Community

sai teja
sai teja

Posted on

Fun with GO Concurrency

For those People who are fascinated about concurrency in GO.
i created a small funny program to understand the concurrency in Go with intuitive example.

Steps:-

  1. Create a buffered channel to hold at-least values in channels will being utilized by two go routines in further
    ch := make(chan int,2)

  2. create two go routines which will consume data from the channel which we created in step 1
    go iAcceptOnlyNegativeFolks(ch)
    go iAcceptOnlyPositiveFolks(ch)

  3. send initial signal/data to the channel
    ch<-1

  4. keep some sleep /use select case / some other strategy to block the main from exiting.
    time.Sleep(time.Millisecond*5)

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 2)

    // initiate +ve & -ve folks
    go iAcceptOnlyNegativeFolks(ch)
    go iAcceptOnlyPositiveFolks(ch)

    // ignite fire between +ve & -ve folks 😅
    ch <- 1

    // this is just simple way to block main else go routines will exit along with main
    time.Sleep(time.Millisecond * 5)

}

func iAcceptOnlyPositiveFolks(ch chan int) {
    for {
        select {
        case x := <-ch:
            if x > 0 {
                fmt.Println(x, " is a positive folk")
                ch <- x + 1
            } else {
                // giving some motivation to -ve folk to become +ve folk
                ch <- x * (-1)
            }
        }
    }
}

func iAcceptOnlyNegativeFolks(ch chan int) {
    for {
        select {
        case x := <-ch:
            if x < 0 {
                fmt.Println(x, " is a negative folk")
                ch <- x - 1
            } else {
                // giving some motivation to +ve folk to become -ve folk
                ch <- x * (-1)
            }
        }
    }
}

sample output 1:-
-1  is a negative folk
-2  is a negative folk
-3  is a negative folk
4  is a positive folk
-5  is a negative folk
-6  is a negative folk
7  is a positive folk
-8  is a negative folk
9  is a positive folk
10  is a positive folk
11  is a positive folk

sample output 2:-
1  is a positive folk
2  is a positive folk
3  is a positive folk
-4  is a negative folk
-5  is a negative folk
6  is a positive folk
7  is a positive folk
Enter fullscreen mode Exit fullscreen mode

Explanation:-

  1. we are creating a buffered channel as a communication medium between two go routines
  2. iAcceptOnlyNegativeFolks & iAcceptOnlyPositiveFolks functions will read data from the channel concurrently (which routine is accessible at that point of time it will read that data from the channel)
  3. After running the above program we will get different out put for every execution because it is running concurrently we don’t know which routine will access the channel data at a point of time.

Please feel free to add any comments/suggestion/ mistakes etc…👍

please follow medium for interesting things

Top comments (0)