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
Something interesting
Tutorials
+13k Golang : Get terminal width and height example
+10.6k Golang : How to delete element(data) from map ?
+5.9k AWS S3 : Prevent Hotlinking policy
+11.6k Android Studio : Create custom icons for your application example
+17k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+5.4k Gogland : Datasource explorer
+7.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+15.6k Golang : Get checkbox or extract multipart form data value example
+9.9k Golang : Sort and reverse sort a slice of integers
+12k Golang : Convert a rune to unicode style string \u
+19.2k Golang : Delete item from slice based on index/key position
+11.5k Use systeminfo to find out installed Windows Hotfix(s) or updates