» Quick Introduction to Go » 3. Advanced » 3.1 Goroutines

Goroutines

Goroutines are a key feature in Go for concurrent programming. Goroutines are lightweight threads managed by the Go runtime, and they allow developers to easily run concurrent tasks concurrently.

package main

import (
	"fmt"
	"time"
)

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

func printLetters() {
	for char := 'a'; char <= 'e'; char++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Printf("%c ", char)
	}
}

func main() {
	go printNumbers() // Start a goroutine to print numbers concurrently
	go printLetters() // Start another goroutine to print letters concurrently

	// Sleep for a while to allow goroutines to execute
	time.Sleep(1 * time.Second)

	fmt.Println("Main function exits.")
    // => 1 a b 2 c 3 4 d e 5 Main function exits.
}

The go keyword is used to start each function as a goroutine. This means that printNumbers and printLetters will run concurrently with the main function.

Code Challenge

Write a program that generates prime numbers up to a given limit concurrently using goroutines.
Note: Ignore make(chan int) and sync.WaitGroup for now. They will be introduced later.

Loading...
> code result goes here
Prev
Next