satori code

|

Michael Trelinski's Technology Blog

Quick threaded app with “Go”

November 19th, 2009 at 19:21

Wow, seriously, hats off to Google on this one…  This should make threaded apps programming easier in the future for me.  They have created a language called “Go”, which in my opinion, looks like if Python and C++ had a child out of wedlock.  I don’t think I’ll be able to stop gushing about Go for a while.  I believe I have found my new prototyping language, however, I don’t see a reason why this couldn’t run production code…

Check out this snippet of Go code:

file: threads.go

package main

 

import "fmt"
import "syscall"

 

const THREADS = 2;

 

func threadtest(a int) {
fmt.Printf("Thread %d started.\n", a);
syscall.Sleep(10);
for true {
for i := 0; i < 10; i++ {
fmt.Printf("Thread %d -> %d \n", a, i);
}
}
}

 

 

func waitforever(debug int) {
for true {
if debug == 1 {
fmt.Printf(".");
} else {
fmt.Printf("");
}
}
}

 

 

func main() {
fmt.Printf("testing threads:\n");
for i := 0; i < THREADS; i++ {
go threadtest(i);
}
waitforever(0);
}

Output:

 

$ ./threads
testing threads:
Thread 0 started.
Thread 1 started.
Thread 0 -> 0 
Thread 1 -> 0 
Thread 0 -> 1 
Thread 1 -> 1 
Thread 0 -> 2 
Thread 1 -> 2 
Thread 0 -> 3 
Thread 1 -> 3 
Thread 0 -> 4 
Thread 1 -> 4 
Thread 0 -> 5 
Thread 1 -> 5 
Thread 0 -> 6 
Thread 1 -> 6 
Thread 0 -> 7 
Thread 1 -> 7 
Thread 0 -> 8 
Thread 1 -> 8 
Thread 0 -> 9 
Thread 1 -> 9 

$ ./threads

testing threads:

Thread 0 started.

Thread 1 started.

Thread 0 -> 0 

Thread 1 -> 0 

Thread 0 -> 1 

Thread 1 -> 1 

Thread 0 -> 2 

Thread 1 -> 2 

Thread 0 -> 3 

Thread 1 -> 3 

Thread 0 -> 4 

Thread 1 -> 4 

Thread 0 -> 5 

Thread 1 -> 5 

Thread 0 -> 6 

Thread 1 -> 6 

Thread 0 -> 7 

Thread 1 -> 7 

Thread 0 -> 8 

Thread 1 -> 8 

Thread 0 -> 9 

Thread 1 -> 9 

True (easy) concurrency!  The magic happens on “go threadtest(…)”, this is called a “goroutine.”  I’ll try to write some more Go-code later… cheers!

Tags: ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CAPTCHA Image CAPTCHA Audio
Refresh Image