From 27356882dee60ccedbc71ce122bb7074f5738b68 Mon Sep 17 00:00:00 2001 From: Rachita Bhagchandani <41795536+rachita18144@users.noreply.github.com> Date: Mon, 19 Nov 2018 07:25:54 +0530 Subject: [PATCH] Updated goroutines guide (#22176) * Updated goroutines guide Added examples and resources * Fixed formatting of code blocks and reverted More Information links --- guide/english/go/goroutines/index.md | 46 ++++++++++++++++++---------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/guide/english/go/goroutines/index.md b/guide/english/go/goroutines/index.md index e5c793e9e7..c3a3af9646 100644 --- a/guide/english/go/goroutines/index.md +++ b/guide/english/go/goroutines/index.md @@ -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: - func say(s string) { - fmt.Println(s) - time.Sleep(100 * time.Millisecond) - fmt.Println(s) - } +```go +func say(s string) { + fmt.Println(s) + time.Sleep(100 * time.Millisecond) + fmt.Println(s) +} +``` - func main() { - go say("hello") - say("world") - } - -Output: +Prefix the function or method call with the keyword `go` and you will have a new Goroutine running concurrently. +Let us try to understand this using as example. + +```go +func goroutine_test(n int) { + for i:= 0; i < n; i++ { + fmt.Println(i) + } +} +``` + +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. + +We can also use anonymous function for declaring goroutines. + +```go +func() { + for i:= 0; i < n; i++ { + fmt.Println(i) + } +} () +``` - world - hello - hello - world - -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: * [A Tour of Go](https://tour.golang.org/concurrency/1)