Golang concurrency: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 2: Line 2:
If you're looking for synchronization primitives (ex. mutexes, semaphores, ... see [[golang synchronization]])
If you're looking for synchronization primitives (ex. mutexes, semaphores, ... see [[golang synchronization]])


= Goroutines =
= Threading =
<blockquote>
<blockquote>
== Limits ==
<blockquote>
Threads are a finite resource. You only have so many CPU cores, and CPU cores can only evaluate one thread at a time.
Go defaults to allowing one thread per core, but you can generally get additional performance by increasing this.
<syntaxhighlight lang="go">
require "runtime"
runtime.GOMAXPROCS(-1)  // show configured max-number of threads
runtime.GOMAXPROCS(2)  // set max-number of threads
</syntaxhighlight>
</blockquote><!-- Limits -->
== Goroutines ==
<blockquote>
{{ TODO |
Is this really true? How are coroutines implemented? }}
Goroutines use green-threads rather than os-threads.<br>
Goroutines use green-threads rather than os-threads.<br>
An OS thread is relatively expensive in setup and memory. One thread is reserved for a particular stack.<br>
An OS thread is relatively expensive in setup and memory. One thread is reserved for a particular stack.<br>
Line 30: Line 47:
</blockquote><!-- Goroutines -->
</blockquote><!-- Goroutines -->


= Threading =
== OS Threads ==
<blockquote>
<blockquote>


</blockquote><!-- Threads -->
</blockquote><!-- OS Threads -->
</blockquote><!-- Threading -->


= Multiprocessing =
= Multiprocessing =

Revision as of 19:30, 6 June 2022

This page is about the methods of concurrency provided by go.
If you're looking for synchronization primitives (ex. mutexes, semaphores, ... see golang synchronization)

Threading

Limits

Threads are a finite resource. You only have so many CPU cores, and CPU cores can only evaluate one thread at a time. Go defaults to allowing one thread per core, but you can generally get additional performance by increasing this.

require "runtime"

runtime.GOMAXPROCS(-1)  // show configured max-number of threads
runtime.GOMAXPROCS(2)   // set max-number of threads

Goroutines

TODO:

Is this really true? How are coroutines implemented?

Goroutines use green-threads rather than os-threads.
An OS thread is relatively expensive in setup and memory. One thread is reserved for a particular stack.
Go abstracts threads/threadpools with goroutines to make threads relatively cheap.

func doThing() {
    fmt.Println("hi")
}

func main() {
    go sayHello()  // <-- run in thread
}

Go functions default to using value objects rather than references.
Depending on your datastructure, this makes goroutines fairly concurrency-safe, since it operates on a copy of the data, rather than the same data.

func printThing(a string) {
    fmt.Println(a)
}


go printThing("abc")

OS Threads

Multiprocessing