Tuesday, February 18, 2014

Golang Has Easy Parallel Loops

In programming, the word easy is somehow associated with java and c# like languages. Now, dot NET has a parallel loops and maybe you can do it in java; but as you come to learn Golang, this pattern will come out naturally as concurrency is its nature. 

Ok below is a sample producer-consumer with parallel loops.
package main

import (

var (
    dummy = []string {
        "oranges", "apple cider", "grapes", "raisins", "adam's apple", "apples lg", "avocado",

func main() {
    c := make(chan string)
    done := make(chan bool)
    // you can create a separte function for the closures below

    go func() {
        for i:=0; i<len(dummy); i++ {
            if strings.Contains(dummy[i], "apple") {
                c <- dummy[i]
        done <- true
    go func() {
        for apples := range c {
    <- done
To run:
1) Save the above in a file myfile.go
2) Execute "go run myfile.go" (to create a executable, use "go build myfile.go")
3) Expected output is:
apple cider
adam's apple
apples lg
(good reads: https://sites.google.com/site/gopatterns/home/updates)