0
0
Goprogramming~5 mins

Concurrent execution model in Go

Choose your learning style9 modes available
Introduction

Concurrent execution lets your program do many things at the same time. This helps it run faster and handle multiple tasks smoothly.

When you want to download files while still letting the user interact with the app.
When you need to handle many users connecting to a server at once.
When you want to run background tasks without stopping the main program.
When processing large data in parts to save time.
When you want to improve performance by using multiple CPU cores.
Syntax
Go
go func() {
    // code to run concurrently
}()

This syntax starts a new goroutine, which is a lightweight thread.

The code inside the function runs at the same time as the rest of the program.

Examples
This starts a new goroutine that prints a message concurrently.
Go
go func() {
    println("Hello from goroutine")
}()
This runs the sayHello function concurrently while main continues.
Go
func sayHello() {
    println("Hello")
}

func main() {
    go sayHello()
    println("Main function")
}
This starts three goroutines, each printing its number.
Go
for i := 1; i <= 3; i++ {
    go func(n int) {
        println("Goroutine", n)
    }(i)
}
Sample Program

This program runs printNumbers in a goroutine while main prints messages. The sleep in main lets the goroutine finish printing.

Go
package main

import (
    "fmt"
    "time"
)

func printNumbers() {
    for i := 1; i <= 5; i++ {
        fmt.Println("Number", i)
        time.Sleep(100 * time.Millisecond)
    }
}

func main() {
    go printNumbers() // run concurrently
    fmt.Println("Main function continues")
    time.Sleep(600 * time.Millisecond) // wait to see goroutine output
    fmt.Println("Main function ends")
}
OutputSuccess
Important Notes

Goroutines are very lightweight compared to traditional threads.

Use time.Sleep or synchronization to let goroutines finish before main ends.

Channels are often used to communicate between goroutines (not shown here).

Summary

Concurrent execution lets your program do multiple things at once.

In Go, goroutines are used to run code concurrently with simple syntax.

Remember to manage timing so goroutines have time to run before the program exits.