Created
June 10, 2020 05:46
-
-
Save akshaybharambe14/0cd65a0b15b1175bfd45989d2afce5eb to your computer and use it in GitHub Desktop.
Simple Ping Pong in Go with go routines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
c := make(chan struct{}) | |
go ping(c) | |
go pong(c) | |
// start the game | |
c <- struct{}{} | |
time.Sleep(time.Second * 10) | |
// stop the game after 10 sec | |
<-c | |
} | |
func play(c chan struct{}, player string) { | |
<-c | |
fmt.Println(player) | |
time.Sleep(time.Second) | |
c <- struct{}{} | |
} | |
func ping(c chan struct{}) { | |
for { | |
play(c, "Ping") | |
} | |
} | |
func pong(c chan struct{}) { | |
for { | |
play(c, "Pong") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment