Updated goroutines guide (#22176)
* Updated goroutines guide Added examples and resources * Fixed formatting of code blocks and reverted More Information links
This commit is contained in:
committed by
Christopher McCormack
parent
522ac6c139
commit
27356882de
@ -9,25 +9,37 @@ Prefix the function or method call with the keyword `go` and you will have a new
|
|||||||
|
|
||||||
Let's look at an example:
|
Let's look at an example:
|
||||||
|
|
||||||
func say(s string) {
|
```go
|
||||||
fmt.Println(s)
|
func say(s string) {
|
||||||
time.Sleep(100 * time.Millisecond)
|
fmt.Println(s)
|
||||||
fmt.Println(s)
|
time.Sleep(100 * time.Millisecond)
|
||||||
}
|
fmt.Println(s)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
func main() {
|
Prefix the function or method call with the keyword `go` and you will have a new Goroutine running concurrently.
|
||||||
go say("hello")
|
Let us try to understand this using as example.
|
||||||
say("world")
|
|
||||||
}
|
|
||||||
|
|
||||||
Output:
|
```go
|
||||||
|
func goroutine_test(n int) {
|
||||||
|
for i:= 0; i < n; i++ {
|
||||||
|
fmt.Println(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
world
|
We just need one single statement `go goroutine_test(10)` to have our goroutine up and running. Usually, when we call a function, our program will execute all the statements in the function and then return to the next statement after the calling statement. But with goroutines, this is not the case. The function executes in a concurrent fashion and our program does not wait for the control to return to the next statement, instead it immediately returns the control to the next statement and executes the function in a separate lightweight thread called goroutines. We can run thousands of goroutines simultaneously. Because of this reason, go is a server friendly language as we can run many tasks at the same time and that too using less memory.
|
||||||
hello
|
|
||||||
hello
|
We can also use anonymous function for declaring goroutines.
|
||||||
world
|
|
||||||
|
```go
|
||||||
|
func() {
|
||||||
|
for i:= 0; i < n; i++ {
|
||||||
|
fmt.Println(i)
|
||||||
|
}
|
||||||
|
} ()
|
||||||
|
```
|
||||||
|
|
||||||
You can observe that since we called `say("hello")` in a goroutine, it'll run concurrently and will print the output in no particular order in regards to the regualar function call `say("world")`.
|
|
||||||
|
|
||||||
#### More Information:
|
#### More Information:
|
||||||
* [A Tour of Go](https://tour.golang.org/concurrency/1)
|
* [A Tour of Go](https://tour.golang.org/concurrency/1)
|
||||||
|
Reference in New Issue
Block a user