Learn Golang
  • Learn Go
  • The Basics
    • Installing Go
    • Hello World
  • Language Features
    • Basic Input Output
    • Variable Basics
    • Control Statements
    • Loops
    • Functions
    • Recursion
  • Data Structures
    • Arrays
    • Slices
    • Maps
    • Pointers
    • Structs
  • Other Concepts
    • Sorting
    • Interfaces
    • Generics
    • Goroutines
  • References
Powered by GitBook
On this page
  1. Other Concepts

Goroutines

Lightweight concurrency and threading

PreviousGenericsNextReferences

Last updated 2 years ago

CtrlK

Go routines are essentially lightweight threads managed by the go runtime. We use the go keyword in front of a function to specify that it is a routine

goroutine_demo.go
package main

import (
  "fmt"
  "time"
)

func main() {
  // run the say function in a goroutine
  go say("world")
  say("hello")
}

// intentionally delay the say function, so simulate a long
// running proccess
func say(s string) {
  for i := 0; i < 5; i++ {
    time.Sleep(100 * time.Millisecond)
    fmt.Println(s)
  }
}
$ go run goroutine_demo.go
hello
world
world
hello
world
hello
world
hello
world
hello