Golang runtime.NumGoroutine() and Gosched() functions example

package runtime

Golang runtime.NumGoroutine() and Gosched() functions usage example.

 package main

 import (
 "fmt"
 "runtime"
 )

 func echo(s string) {
 for i := 0; i < 5; i++ {
 runtime.Gosched() // allow switching between the scheduled routines 
 fmt.Println(s)
 }
 }

 func main() {

 // maximize CPU usage for multi threading
 runtime.GOMAXPROCS(runtime.NumCPU())

 go echo("bye") // schedule this execution on a new thread [second]

 go echo("world") // [third]

 echo("good") // current [first thread]

 fmt.Println("# go routines : ", runtime.NumGoroutine())
 }

NOTE : "In programming, concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations. Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once."

For example :

Concurrency : Send email, render PDF file, send out push notification using multiple core processors within 1 second. - different task at the same time

Parallel - Send many emails out using multiple core processors within 1 second. - similar task at the same time

SEE ALSO : https://www.socketloop.com/tutorials/golang-concurrency-and-goroutine

References :

http://golang.org/pkg/runtime/#NumGoroutine

http://golang.org/pkg/runtime/#Gosched

https://www.socketloop.com/tutorials/golang-concurrency-and-goroutine

Advertisement