Concurrency in Golang

Tram Ho

Hello everyone, due to work fluctuations, I also switched to learn a little about Golang. Today I would like to share with everyone a little knowledge about Concurrent in Golang. I translated from the book Go in Action. Any suggestions, please leave them in the comments. Thanks guys so much. Start:

Concurrency

  • One difficult task for a programmer is to write a program that efficiently uses the resources of the hardware that the program will run. Modern computers have lots of cores, but most programming languages ​​don’t have the tools to help programmers make the best use of those resources. They often require a lot of code to synchronize the thread (thread) leading to error prone.
  • Concurrency is one of the most powerful features of Go. Goroutines are like Thread , but use much less memory and require less code to use. Channels is a data structure that allows you to send messages between goroutines in a supported synchronization from Go. This creates a programming model in which you send messages between goroutines instead of goroutines fighting to share the same data. Now let’s find out more details.

Goroutines

Goroutines are functions that run concurrently with other goroutines, including the entry point (main function) of the program. In other languages, you use threads to do the same thing, but in Go many goroutines execute on one thread. For example, if you write a webserver and you want to process multiple requests simultaneously, you would write a lot of code to use threads in C or Java. In Go, the net / http package supported handling multiple requests simultaneously using goroutines . Each incoming request will be automatically run on its own goroutine. Goroutines use less memory than thread, and the Go runtime automatically schedules the execution against a preconfigured set of logic processors. Each processor logic is associated with an OS thread. If you want to execute a few pieces of code simultaneously while you move on to another job, goroutine will help you get there. Check out the example below:

The go keyword is all you need to plan the log functionality to run as a goroutine and run concurrently with other goroutines. This means that you can continue to execute any remaining code in your program while logging occurs concurrently. As stated earlier, goroutines have minimal cost so can generate millions of goroutines =)). This I will share more in the following sections.

I will stop writing here. Next post I will share about Channels .

Hope these theoretical knowledge will help you have a look at Golang and Concurrency in Golang.

Thanks everyone and see you again.

Share the news now

Source : Viblo