package
0.0.0-20240301224925-0cef28b8b45b
Repository: https://github.com/akarshippili/golang.git
Documentation: pkg.go.dev
# README
Go make it simple to build
- fan-in model
- fan-out model
whole idea is that we can balance out level of concurrency to make our app/programs effecient.
In go workers -> goroutines and they use channels to communicate to implement concurrency.
goroutine
is a function executing concurrently with other goroutines in the same address spaces (i.e within the same program/process). it is lightweight costing little more than the allocation of stack space.
few more points on goroutine
- sheduled by go runtime // scheduler
- lighter than threads
- go manages goroutines
- fewer context switchs.
- lesser threads
- fast startups
- comminicate via channels
waitGroups
is simply a counter that have a special behaviour when they a value equal to zero. we can increase it or decrease it
waitGroups Api
func (wg waitGroup) Add(int delta) -> increments counter by delta
func (wg waitGroup) Done() -> decrements counter by one
func (wg waitGroup) Wait() -> this is the special behaviour, this simply blocks wherever its called untill counter becoms zero
Demo:
func main(){
// anonymous function
// to make a func to goroutine is to add go key word in front of it.
go func(){
fmt.Println("async thing")
}()
}
Explaination.
1.here we are creating a goroutine.
2.we are making a request to go scheduler to schedule the goroutine in the future.
3.but it gets terminated as soon as the we exith the main function. the go runtime get notified but did not get the time to schedule the goroutine.
4.for solve the same we use waitGroups.
func main(){
var wg sync.WaitGroup
wg.Add(1)
go func(){
fmt.Println("async thing")
wg.Done()
}()
wg.Wait()
}
channels
Help to synchronize and to communicate b/w goroutines.
ch := make(chan <type>)
Operations:
- send message to a channel
- read message from a channel
(similar to a message queue)
sending message to a channel
ch <- "Hello!!!"
reading message from a channel
msg := <- ch
Note: Block until complementory operation is ready.
select with channel
func SelectChannelTest() {
ch1, ch2 := make(chan string), make(chan string)
go func() {
select {
case msg1 := <-ch1:
fmt.Println(msg1)
case msg2 := <-ch2:
fmt.Println(msg2)
}
}()
go func() {
ch1 <- "Hello"
}()
go func() {
ch2 <- "World"
}()
time.Sleep(5 * time.Millisecond)
fmt.Println("Done!")
}
looping through channel
for msg := range ch {
fmt.Println(msg)
}