In this blog, let us discuss a program to visualize concurrency in Golang.
Reference and source:
Program 1:
| import "fmt" | |
| import "time" | |
| func main() { | |
| var Ball int | |
| Ball = 5 | |
| table := make(chan int) | |
| go player(table, 1) | |
| go player(table, 2) | |
| fmt.Println("mainstart:", Ball) | |
| table <- Ball | |
| time.Sleep(1* time.Second) | |
| endres := <-table | |
| fmt.Println("mainend:", endres) | |
| } | |
| func player(table chan int, playernumber int){ | |
| for{ | |
| ball := <-table | |
| fmt.Println(playernumber,":",ball) | |
| ball++ | |
| time.Sleep(100 * time.Millisecond) | |
| table <- ball | |
| } | |
| } |
/* ----------------------------------------------------------------------------------------------------------
Explanation:
Please try to visualize on your own before reading the explanation.
We will name the two goroutines that are called as player1_goroutine and player2_goroutine
Only when the chan table has some data, it can be read. Both the goroutines are initially waiting to read but the chan is empty, so when "table <- Ball" is executed, table has data and ball := <-table in player1_goroutine will read the data from chan.
Now, player2_goroutine is waiting to read data from table and in the last line of the player method we write the ball value to table. Now, player2_goroutine will read the data from the channel.
This continues until the endres variable reads the data from the channel after a sleep time of 1 second.
That's why we can see player 1 and player 2 read data from the channel in an alternate manner and write it back till the channel read in the main method is invoked after sleep time.
---------------------------------------------------------------------------------------------------------- */
Comments
Post a Comment