0
0
Goprogramming~5 mins

Why concurrency is needed in Go

Choose your learning style9 modes available
Introduction

Concurrency lets a program do many things at the same time. This helps it work faster and handle many tasks without waiting for one to finish before starting another.

When you want to download multiple files at once without waiting for each to finish.
When a program needs to listen for user input while also doing background work.
When you want to handle many users connecting to a server at the same time.
When you want to keep a program responsive while doing slow tasks like reading from disk.
When you want to split a big job into smaller parts that run together to finish faster.
Syntax
Go
go func() {
    // code to run concurrently
}()
In Go, concurrency is often done using goroutines, which are lightweight threads.
The keyword go starts a new goroutine to run the function concurrently.
Examples
This starts a new goroutine that prints a message without blocking the main program.
Go
go func() {
    println("Hello from a goroutine")
}()
This runs the doWork function concurrently using a goroutine.
Go
go doWork()

func doWork() {
    println("Working concurrently")
}
Sample Program

This program runs say("Hello") in a new goroutine while say("World") runs in the main goroutine. You see messages from both at the same time.

Go
package main

import (
    "fmt"
    "time"
)

func say(message string) {
    for i := 0; i < 3; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(message)
    }
}

func main() {
    go say("Hello")
    say("World")
    time.Sleep(500 * time.Millisecond) // Added to allow goroutine to finish
}
OutputSuccess
Important Notes

Goroutines are very cheap and easy to create compared to traditional threads.

Without concurrency, programs wait for one task to finish before starting another, which can be slow.

Concurrency helps programs stay responsive and use resources efficiently.

Summary

Concurrency lets programs do many things at once.

Go uses goroutines to run code concurrently.

This makes programs faster and more responsive.