Understanding the concurrency model is sometimes an early pain point for programmers—not just for Go, but across languages that use different models as well. Part of this is due to operating in a black box (depending on your terminal preferences); a developer has to rely on logging or errors with data consistency to discern asynchronous and/or multiple core timing issues.
As the concepts of synchronous and asynchronous or concurrent and nonconcurrent tasks can sometimes be a bit abstract, we will have a bit of fun here in an effort to demonstrate all the concepts we've covered so far in a visual way.
There are, of course, a myriad of ways to address feedback and logging. You can write to files in console/terminal/stdout…
, most of which are inherently linear in nature. There is no concise way to represent concurrency in a logfile. Given this and the fact that we are dealing with an emerging language with a focus on servers, let's take a different angle.
Instead of simply outputting to a file, we'll create a visual feedback that shows when a process starts and stops on a timeline.
To show how approaches differ, we'll create a simple web server that loops through three trivial tasks and outputs their execution marks on an X-second timeline. We'll do this using a third-party library called svgo
and the built-in http
package for Go.
To start, let's grab the svgo
library via go get
:
go get github.com/ajstarks/svgo
If you try to install a package via the go get
command and get an error about $GOPATH
not being set, you need to set that environment variable. GOPATH
is where Go will look to find installed import packages.
To set this in Linux (or Mac), type the following in bash (or Terminal):
export GOPATH=/usr/yourpathhere
This path is up to you, so pick a place where you're most comfortable storing your Go packages.
To ensure it's globally accessible, install it where your Go binary is installed.
On Windows, you can right-click on My Computer and navigate to Properties | Advanced system settings | Environment Variables…, as shown in the following screenshot:
Here, you'll need to create a new variable called GOPATH
. As with the Linux and Mac instructions, this can either be your Go language root directory or someplace else entirely. In this example, we've used C:Go
, as shown in the following screenshot:
Now that we have installed gosvg, we can visually demonstrate how the asynchronous and synchronous processes will look side-by-side as well as with multiple processors.
More libraries
Why SVG? We didn't need to use SVG and a web server, of course, and if you'd rather see an image generated and open that separately, there are other alternatives to do so. There are some additional graphical libraries available for Go, which are as follows:
Robust GUI toolkits are also available, but as they were designed as systems languages, it isn't really Go's forte.