How Golang makes concurrent programming easier
In this article we will explore how Golang makes the use of concurrent threads more easy.
Goroutines
Goroutine is a function that runs concurrently with other goroutines inside the same program. They are ligth and eficient allowing that you execute countless goroutines.
Different of traditional threads Goroutines are managed by Go internally, make the use of them more easy for the developer, providing a better developer experience in use.
How use?
Now that we know what goroutines are, let’s see a real-world example of how to use them.
Recommended by LinkedIn
go createGoRoutine()
To create a goroutine, we simply add the go keyword before the function call, and Go will handle the rest automatically.
We can also use anonymous functions with goroutines. Let’s look at an example:
This example is from an application where we listen to WebSocket messages from Binance and check if a cryptocurrency is close to a target buy price.
go func() {
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Printf("Error reading message: %v", err)
return
}
var trade TradeMessage
if err := json.Unmarshal(message, &trade); err != nil {
log.Printf("Error processing message: %v", err)
continue
}
log.Printf("New trade: %s - Price: %s", trade.Symbol, trade.Price)
}
}()
📌 What happens here?
Goroutines make concurrent programming simpler and more efficient. In the next section, we can explore channels, which allow secure communication between goroutines.
Full Stack Software Engineer | Front-end focused | ReactJS | React Native | NodeJS | AWS
2moVery interesting! Thanks for sharing
Lead Fullstack Engineer | Typescript Software Engineer | Nestjs | Nodejs | Reactjs | AWS
2moCool! Looking forward to checking it out.
Senior Backend NodeJS | Speaker at Google GDG for AI | Kotlin | MVVM | Fastify | Coroutines | Koin | SOLID | Unit Tests | Instrumented Tests | GraphQL | Knex.js
2moGreat post!
Senior Frontend Developer | Mobile Developer | React | React Native | Flutter | Fastlane
3moGolang’s goroutines are a game-changer for concurrent programming. They’re lightweight, easy to use, and managed by Go’s runtime, making parallel execution much simpler compared to traditional threads. Using goroutines with WebSockets, as in your example, keeps the main program responsive while processing messages in the background. Looking forward to your take on channels!
Full Stack Engineer | React.js | Node.js | NextJS | AWS
3moNice article Renan Machado Pinho!