Created
November 30, 2024 06:50
-
-
Save dipamsen/e196e83b6dd755094fa412142bf72827 to your computer and use it in GitHub Desktop.
Channels and Goroutines (Go)
This file contains hidden or 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 worker(done chan int) { | |
time.Sleep(time.Second) | |
done <- 2000 | |
} | |
func main() { | |
// buffered channel === queue | |
// channel ~ portal to send data | |
// messages := make(chan string)// unbuffered, the "send" blocks until a "recv" happens (deadlock) | |
// // go func() { | |
// messages <- "ping" | |
// // messages <- "pong" | |
// // }() | |
// msg := <-messages | |
// // msg2 := <-messages | |
// fmt.Println(msg) | |
// // fmt.Println(msg2) | |
messages := make(chan string, 10) // buffered, send is non blocking and stores stuff until recved | |
messages <- "ping" | |
messages <- "pong" | |
fmt.Println(<-messages) | |
fmt.Println(<-messages) | |
done := make(chan int) | |
go worker(done) // async function call | |
fmt.Println(<-done) // await | |
c1 := make(chan int, 1) // buffered, useful so that "send" isn't blocking (when no recver) | |
c2 := make(chan int, 1) | |
go func() { | |
c1 <- 23 | |
}() | |
go func() { | |
c2 <- 34 | |
}() | |
select { // blocks until one of the channels recv, first to resolve wins | |
case msg1 := <-c1: | |
fmt.Println(msg1) | |
case msg2 := <-c2: | |
fmt.Println(msg2) | |
case <-time.After(time.Second): | |
fmt.Println("time out") | |
// use default for a non blocking recv (if no one resolves immmediately) | |
} | |
ch := make(chan string) | |
select { | |
case ch <- "hi": // no immediate recver, not buffered | |
fmt.Println("sent message hi") | |
default: // non blocking send | |
fmt.Println("no message sent") | |
} | |
jobs := make(chan int) | |
don := make(chan bool) // for awaiting | |
go func() { // worker | |
for { | |
j, more := <-jobs // second return value is false if channel closes | |
if more { | |
fmt.Println("received job", j) | |
} else { | |
fmt.Println("received all jobs", j) | |
don <- true | |
return | |
} | |
} | |
}() | |
for j := 1; j <= 3; j++ { | |
jobs <- j | |
fmt.Println("sent job", j) | |
} | |
close(jobs) // close channel | |
fmt.Println("sent all jobs") | |
<-don // await worker | |
queue := make(chan int, 5) | |
queue <- 5 // sends are not blocking | |
queue <- 4 | |
queue <- 3 | |
queue <- 2 | |
queue <- 1 | |
close(queue) | |
for v := range queue { | |
fmt.Println(v) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment