Friday, March 3, 2017

golang run code at timed intervals

If you come from a Javascript background, you might be accustomed to setInterval.

In Golang if you want to run code a set interval you would do the following.

package main

import (
"fmt"
"time"
)

func main() {
ticker := time.NewTicker(time.Second)
for time := range ticker.C {

fmt.Printf("we run at %s\n", time.String())
}
}

The code inside will be called every second, as defined in time.NewTicker().

Thursday, March 2, 2017

multiple goroutines reading a buffered channel

I wrote the following code to demonstrate multiple goroutines processing a single goroutine in response to a question from the Go Forum.

package main

import (
"fmt"
"time"
)

func main() {
queue := make(chan string, 10000)

// we can use a waitgroup but this works too
waitUntilDone := make(chan bool)

// input random data into the goroutine
go feedme(queue)

// we make sure to use our 4 core gigawatt cpu
// by spinning up 4 goroutines to process the incoming
// data in the `queue` goroutine
for i := 0; i < 4; i++ {
go func(queue chan string, i int) {
for {
data := <-queue
fmt.Printf("data received by goroutine %d!!: %s\n", i, data)
}
}(queue, i)
}

<-waitUntilDone
}

func feedme(q chan string) {
ticker := time.NewTicker(time.Millisecond * 250)
for t := range ticker.C {
q <- t.String()
}
}



waitforme waitgroup shouting

package main

import (
"fmt"
"sync"
)

func main() {
waitforme := &sync.WaitGroup{}
for i := 0; i < 200; i++ {
// add for each operation
waitforme.Add(1)
go shout(waitforme)
}

// wait for all to complete otherwise Go quits automatically!!!
waitforme.Wait()
}

func shout(waitgroup *sync.WaitGroup) {
fmt.Println("whoo hooo")

// done for each completed operation
waitgroup.Done()
}

Code Golang efficiently in Sublime Text 3 with GoSublime

Vim is terrible. There are 20 keypresses to editing a 6 line column rather than the 5 clicks it takes in Sublime Text.

You can use Sublime Text with all the helpers that Go provides (gofmt) automatically by installing GoSublime.

1. Install Sublime Text 3

Download and install Sublime Text 3 from the official application website.


2. Install PackageControl in Sublime Text 3

PackageControl for Sublime Text 3 is the most essential plugin for installing other packages. You can either install from the console or install through the helper included with Sublime Text.


3. Install GoSublime

After you have installed PackageControl, simply go to the preconfigured actions (Cmd + Shift  + P) then type in Package Control: Install Package.

Then type in GoSublime, and you are good to go!