View : 0

12/04/2026 18:15pm

EP.8 Go and Goroutines - Mastering Concurrent Work Like a Pro!

EP.8 Go and Goroutines - Mastering Concurrent Work Like a Pro!

#application development

#sync

#Channels

#Concurrency

#Goroutines

#Go

Go and Goroutines - Mastering Concurrent Work Like a Pro!

Do you want your program to perform multiple tasks quickly? Today, we will teach you how to use Goroutines and Channels in Go that will make your program run smoothly and efficiently.

 

What are Goroutines?
A Goroutine is a lightweight processing unit that Go uses for concurrent operations. When we create a Goroutine, Go runs it in the background without blocking the main program, allowing us to run multiple tasks simultaneously.

Example of a Goroutine:

package main

import (
    "fmt"
    "time"
)

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

func main() {
    go printNumbers() // สร้าง Goroutine
    fmt.Println("Goroutine started")
    time.Sleep(3 * time.Second) // รอให้ Goroutine ทำงานเสร็จ
}

 

Channels: Communication Between Goroutines
Channels are used to send data between Goroutines, making concurrent operations safer and more organized.

Example of a Channel:

func main() {
    messages := make(chan string)

    go func() {
        messages <- "Hello from Goroutine" // ส่งข้อมูลผ่าน Channel
    }()

    msg := <-messages // รับข้อมูลจาก Channel
    fmt.Println(msg)
}

 

Buffered Channels:
Channels can be buffered to hold multiple values:

func main() {
    messages := make(chan string, 2) // บัฟเฟอร์ได้ 2 ค่า

    messages <- "First"
    messages <- "Second"

    fmt.Println(<-messages)
    fmt.Println(<-messages)
}

 

Controlling Concurrency with sync
Go has a sync package for controlling concurrency, such as waiting for Goroutines to finish:

import (
    "fmt"
    "sync"
)

func worker(wg *sync.WaitGroup, id int) {
    fmt.Printf("Worker %d starting\n", id)
    wg.Done() // ลดตัวนับลง 1
}

func main() {
    var wg sync.WaitGroup

    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go worker(&wg, i)
    }

    wg.Wait() // รอให้ทุก Goroutine ทำงานเสร็จ
    fmt.Println("All workers done")
}