Golang concurrency: Difference between revisions

From wikinotes
(Created page with "= Goroutines = <blockquote> 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 par...")
 
Line 13: Line 13:
     go sayHello()  // <-- run in thread
     go sayHello()  // <-- run in thread
}
}
</syntaxhighlight>
Go functions default to using value objects rather than references.<br>
Depending on your datastructure, this makes goroutines fairly concurrency-safe, since it operates on a copy of the data, rather than the same data.
<syntaxhighlight lang="go">
func printThing(a string) {
    fmt.Println(a)
}
go printThing("abc")
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Goroutines -->
</blockquote><!-- Goroutines -->

Revision as of 17:36, 6 June 2022

Goroutines

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")

Threading

Multiprocessing