I had a nice day so far delving into go, and already tried a few
things to get accustomed to it. So far, so good, and for some reason I
do like the language !
It would probably be a nice coding practice to implement something
like git in it (
http://gitorious.org/gogit ), but lets leave that as
a side note ;).
My actual question is about goroutines and how to make them occupy
multiple threads. I thought that two goroutines would be executed in
two threads already, but that does not happen on my side using release.
2009-11-10.1.
This is my example Test - I monitored the actual use of cores using
the system monitor, but even the output gives some hints here. The
following code is compiled and executed using gotest:
func every( out chan<- uint, number uint ) {
c := uint(2);
for {
if c % number == 0 {
out <- c;
}
c += 1;
}
}
func TestChannelThreading(t *testing.T) {
result := make( chan uint, 10 );
// should take a while - would expect at least 2 threads here
go every( result, 100000000 );
go every( result, 50000001 );
// get some values
for i := 0; i < 20; i++ {
fmt.Println( "Got result: ", <-result );
}
}
The output is:
Got result: 100000000
Got result: 200000000
Got result: 300000000
Got result: 400000000
Got result: 500000000
Got result: 600000000
Got result: 700000000
Got result: 800000000
Got result: 900000000
Got result: 1000000000
Got result: 1100000000
Got result: 50000001
Got result: 1200000000
Got result: 100000002
Got result: 1300000000
Got result: 150000003
Got result: 1400000000
Got result: 200000004
Got result: 1500000000
Got result: 250000005
Besides the fact that the system monitor only shows one CPU ( of my
two cores ) being used, the coroutines run unbalanced as well. The
first routine should take about twice as long to produce a value, yet
it produces most of the values. In the end of the run, the second one
catches up somewhat, but it is just as fast, not twice as fast, as the
first one.
The channel I use is buffered, hence blocking should not be infered by
it. I also made another test with two distinct buffered channels and a
select clause, but had no more luck there neither.
Does anybody know what I am missing here ? Is the test not catching
the actual idea of coroutines ?
Thank you