English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Golang Miscellaneous

Go Language Multiple Goroutines

Goroutine is a function or method that can be executed independently and concurrently with any other Goroutine existing in the program. In other words, each activity that executes simultaneously in the Go language is called a Goroutine. In Go language, you are allowed to create multiple goroutines in a program. You can simply create a goroutine by using the 'go' keyword as a prefix for function or method calls, as shown in the following syntax:

func name(){}
// statement
}
//Create goroutine using the go keyword
go name(),

Now, with an example, let's discuss how to create and use multiple goroutines:

package main
import (
    "fmt"
    "time"
)
//goroutine 1
func Aname() {
    arr1 := [4]:string{"Rohit", "Suman", "Aman", "Ria"}
    for t1 := 0; t1 <= 3; t1++ {
        time.Sleep(150 * time.Millisecond)
        fmt.Printf("%s\n", arr1[1}
    }
}
// goroutine 2
func Aid() {
    arr2 := [4]:int{300, 301, 302, 303}
    for t2 := 0; t2 <= 3; t2++ {
        time.Sleep(500 * time.Millisecond)
        fmt.Printf("%d\n", arr2[2}
    }
}
func main() {
    fmt.Println("!...Main Go",-routine begins...!
    // Call Goroutine 1
    go Aname(),
    // Call Goroutine 2
    go Aid(),
    time.Sleep(3500 * time.Millisecond)
    fmt.Println("\n!...Main Go",-routine ends...!
}

Output:

!...Main Go-routine begins...!
Rohit
Suman
Aman
300
Ria
301
302
303
!...Main Go-routine ends...!

Create:In the above example, in addition to the main goroutine, we also have two goroutines, namelyAnameandAid. Here,AnamePrint the author's name,AidPrint the author's id.

Work:Here, we have two goroutines, namelyAnameandAid,as well as a main goroutine. When we first run the program, the main goroutine is layered and prints "!...Main Go"-routine begins...! Here, the main goroutine is like a parent goroutine, and other goroutines are its child processes. Therefore, the main goroutine is run first, and then other goroutines are started. If the main goroutine terminates, other goroutines also terminate. Therefore, after the main goroutine,AnameandAid goroutine will begin working simultaneously. The Aname goroutine starts from15Work begins at 0ms, while Aid starts from500ms Start Working.