Each thing I learn in Go, I find myself trying to refer to it as I would in another language (thinking of structs as Classes, for example.)
There are however some differences with the Go implementation of these concepts. In this post I wanted to take some material I’ve been reading about and learning about in various courses and books. Specifically, I’d like to refer to the concept of concurrency.
A goroutine is a way of running functions concurrently. In Grails there is a concept of using “promises” and tasks… and this is kinda similar. But keep in mind that concurrent doesn’t necessarily mean parallel.
In my Port Scanner, I was originally running each check on a port in a range sequentially. It would take several min to iterate over a list of 8000 ports. However, when I applied the concept of GoRoutines, I got this down to 20 seconds to run over 8,000 localhost ports.
Setting Up GoRoutines
To make use of GoRoutines we need to define a wait group. The concept of a WaitGroup works like this:
- we define a wait group
- we define how many groups (concurrent functions) we’ll be doing
- we call the function using the “go” keyword (defining it as a Go Routine)
- Once the function process is done, we mark the group as done.
In practicality it would look like this:
The first line defines the variable wg to hold the value for the WaitGroup method of the sync package (which will need to be imported.)
wg then makes use of the built in method Add() and in this case I put in the value of 4 wg.Add(4) which will run 4 concurrent runs.
Each concurrent call is defined as:
go [function name](params)
In this case:
go check_port(host, start_port, end_port_set1)…
At the bottom of this list of calls there’s a wait invoked: wg.Wait()
Lastly, the function itself has a wg.Done() at the end of the logic.
Channels in Go
Channels are a complex subject for me. At first, I thought it was the magic that made concurrency happen in Go. Instead, I discovered that GoRoutines are how concurrency is applied in a go app. Channels offer the ability for GoRoutines to share data back and forth.
I initially thought of channels as a “Thread,” as in other languages.
However, in reading this programmer’s blog post, I discovered some differences to threads: http://tleyden.github.io/blog/2014/10/30/goroutines-vs-threads/
You can see their full bulleted list of differences there. I’ll just mention a couple highlights:
- GoRoutines can be run at a factor more than Threads on a system.
- GoRoutines have a mechanism to share and talk between GoRoutines (channels.)
Channels are mechanisms to share data between GoRoutines.
More info on channels: