[Go Lang] Basic golang programming – Goroutine

Tram Ho


Through a few introductions about the golang programming language, everyone also knows about the strength of the day language is the ability to handle multithreading, it is one of the issues that golang developers focus on. Go offers two very powerful features that support concurrency: Goroutine and Channel.
This article will introduce Goroutine in Go

Goroutine concept

  • Goroutine is a function that can run concurrently with other functions.
  • Goroutines are lightweight streams, initialized with only 2KB in the stack size, which can increase or decrease memory space depending on usage requirements.
  • Go apps can have lots of Goroutines running simultaneously.

Mechanism of action and usage

  • The mechanism of goroutine is quite simple: a function exists in a multithreaded way with other goroutines in the same memory space, Go has a controller that manages goroutines and then distributes them into logical processors and attaches them. Each of these logic processors has a system thread previously created to execute these goroutines. In other words, each system thread will handle a coordinated goroutine group through the logic processor. With the simultaneous task management controller and the logic processor mechanism, the difficulties and hassles when declaring the Go thread have already dealt with for us.
  • To initialize a goroutine we just need to prepend a function call or method call with the keyword go
    For example, sequentially display numbers from 1 to 20 without goroutine

The above example has 2 functions
g1 (): shows the numbers from 1 to 10
g2 (): display numbers from 11 to 20
Because g1 () is written before g2, g1 will execute before g2 (), then g2 () will have to wait for g1 () to complete and the results will display numbers 1 to 20 sequentially.
For example, the sequential display of numbers from 1 to 20 uses goroutine

The above example has two functions, g1 () and g2 (), we add the keyword go before the function name to show that this is the function goroutine, then the functions g1 () and g2 () will be executed simultaneously without we need to wait for the function before it completes, we add the keyword go before the commands fmt.Println(i) and fmt.Println(j) to let the program know these commands are executed simultaneously.
The time.Sleep(time.Second) command is for the main sleep program for 1 second to wait for the two functions g1 (), and g2 () to finish. And this is the result of the above program.
You try to run the above code many times to see that each time you run the results will be different.

End

This article I have introduced the most basic about goroutine in golang, you should practice and make simple examples to better understand it, the next article I will write about sync.Mutex and Channel .
Thanks and see you again =)

Share the news now

Source : Viblo