DEV Community

loading...
Cover image for  Concurrency in Golang

Concurrency in Golang

iambenkay profile image B_aaS ・1 min read

In golang, concurrency is made possible through the use of goroutines and channels.
goroutines are basically "thread-like" lightweight structures that complete activities without blocking the main thread. They are basically a "fire and forget" cause go cleans up when a goroutine is completed. If however, we want to get data out of our goroutine process when it is done then we can use channels.

import "fmt"

// Essentially this is how we fire a goroutine

func runForAWhile(){
  // do something pretty that takes 5 secs or 2 yrs
}

func main(){
  go runForAWhile()
  fmt.Println("I am not waiting for that...")
}
Enter fullscreen mode Exit fullscreen mode

Once we use the go keyword, Go knows to send the operation of that function out of the main scope and continue executing the rest of the code. The program does not end however until the goroutine is complete.
When you run the above example, you'd notice that the Println statement runs almost instantly while the program itself ends after the goroutine has supposedly ended.
Channels are an effective way to wait on output from our goroutine before ending the program. Let's say we made two API calls using two goroutines, we surely want to get that result back into the main scope. Here is an example code that describes how you could achieve that:

import "fmt"

func apiRequest1(c chan string){
  var result string
  result = makeApiCall1()
  c <- result
}

func apiRequest2(c chan string){
  var result string
  result = makeApiCall2()
  c <- result
}

func main(){
  var channel1, channel2 chan string
  go apiRequest1(channel1)
  go apiRequest2(channel2)

  result1 := <- channel1
  result2 := <- channel2

  fmt.Println(result1, result2)
}
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

pic
Editor guide
Collapse
nino71755865 profile image
mei er

great $$$