Sunday, June 3, 2012

golang goroutine Example Sample Code



I don't think basic use of pthreads is that different in complexity from goroutines but it's neat to see lightweight threads as a built-in language feature. goroutine usage superficially looks a lot like costates in Dynamic C, a proprietary nonstandard compiler for the Rabbit series of Z80 derived CPUs from Digi International. It's a really useful feature on a single core 8-bit microcontroller that frees you having "one big loop" with brittle timing in an embedded application.

Code:

package main

import (
"fmt"
"runtime"
"time"
)


func thread1(counter chan int) {
count := 0
for {
fmt.Println("Hello from thread 1")
runtime.Gosched() // force yield
time.Sleep(5 * time.Second)

count++
counter <- count
}
}

func thread2(counter chan int) {
count := 0
for {
 fmt.Println("Hello from thread 2")
 runtime.Gosched() // force yield
 time.Sleep(5 * time.Second)

 count++
 counter <- count
}
}

func main() {
c1 := make(chan int)
c2 := make(chan int)

go thread1(c1)
go thread2(c2)

for {
  count1 := <-c1
  count2 := <-c2
  fmt.Println("main() is alive ", count1, count2)
   time.Sleep(5 * time.Second)
 runtime.Gosched() // force yield
}
}

Output:

Hello from thread 1
Hello from thread 2
Hello from thread 1
Hello from thread 2
main() is alive  1 1
Hello from thread 2
Hello from thread 1
main() is alive  2 2
main() is alive  3 3
Hello from thread 2
Hello from thread 1
main() is alive  4 4
Hello from thread 2
Hello from thread 1
main() is alive  5 5
Hello from thread 2
Hello from thread 1
main() is alive  6 6
Hello from thread 1
Hello from thread 2




Tour golang Exercise: Maps #45 WordCount Solution



This exercise from the golang tour asks for a function that will count the number of times each word appears in a string. I think of it as using a hash to contain a histogram of word frequency. The if/else could be tighter if go had a ternary operator.


Code:


package main

import "strings"
import "fmt"

func WordCount (s string) map[string]int {

    substrs := strings.Fields(s)
    fmt.Println(substrs)

    // key,value  ==> word,count
    // iterate over substrs, if key in map, value++, else create

    counts := make(map[string]int)

    for _, word := range substrs {
        _, ok := counts[word]

        if ok == true {
          counts[word] += 1
        } else {
          counts[word] = 1
        }
    }

    return counts
}

func main() {
  fmt.Println(WordCount("now is the now is the go go go it a a a a a"))
  fmt.Println(WordCount("1 2 3 11 22 33 1 2 3"))
}

Output:

[now is the now is the go go go it a a a a a]
map[now:2 the:2 go:3 a:5 is:2 it:1]
[1 2 3 11 22 33 1 2 3]
map[2:2 33:1 1:2 11:1 22:1 3:2]

Common Error:

./wordcount2.go:20: cannot convert true to type int
./wordcount2.go:20: invalid operation: ok == true (mismatched types int and bool)

This occurs when attempting: 

    ok := counts[word]

Instead of:
    
    _, ok := counts[word]