Goroutines
Go came to existance to solve problems being faced by today’s software, one of them is concurrency. Sol lets first understand what is concurrency?
In computer science, concurrency is the ability of different parts or units of a program, algorithm, or problem to be executed out-of-order or in partial order, without affecting the final outcome. This allows for parallel execution of the concurrent units, which can significantly improve overall speed of the execution in multi-processor and multi-core systems. In more technical terms, concurrency refers to the decomposability property of a program, algorithm, or problem into order-independent or partially-ordered components or units.[1]
In simpler terms, Concurrency in computer programs is ability to execute pieces of program in parellel while providing control and communication among them. The execution of said pieces of programs can be in out of order or in partial order. To solve this Go has special construct called goroutines to execute pieces of programs in parallel.
Let see a how a goroutine can be defined in Go
In illustration above, while variables a
, b
and c
happens in current goroutine but execution of someFunc
happens in seperate goroutine. One can imagine goroutines as lightweight threads that are scheduled and controlled by Go. Goroutines runs in same shared address space so access to shared memory should be synchronised, go provides several primitives in sync
package
By default, main function of package in go is run concurrently, implicitly. For expliit call we pass code block(that needs to be executed in routine) to go
Notice fmt.Scanln(&get)
; this actually makes our main program to wait for inputs, otherwise it will exit before go routine actualy can print. A problem with this code is that, it looks synchronous, in order. To actually see that if goroutine are asynchronous, we need to make goroutine sleep for random time. Lets rewrite above illustration as:
Look at this, now it is random. This illustrates that go routine are independent to each other and runs separately.
Now what we showcased so far is called parallelism, we still need to make them communicate to each other and channels
comes to our rescue. Channels provide a mechanism of communication and synchronisation among goroutines. Lets look at example.
That’s interesting. This is just a simple example of channels
capabilities, there is much more that we have for channels in out next chapter.
Last updated