﻿<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Go Program - The First internet site for Go programming</title>
	<atom:link href="http://www.go-program.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.go-program.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Thu, 19 Nov 2009 11:31:18 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Concurrency</title>
		<link>http://www.go-program.com/concurrency/</link>
		<comments>http://www.go-program.com/concurrency/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 11:31:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=93</guid>
		<description><![CDATA[Concurrency issues
Many issues, of course, but Go tries to take care of them. Channel send and receive are atomic. The select statement is very carefully defined and implemented, etc.
But goroutines run in shared memory, communication networks can deadlock, multithreaded debuggers suck, and so on.
Go gives you the primitives
Don&#8217;t program the way you would in C [...]


Related posts:<ol><li><a href='http://www.go-program.com/channels-in-go/' rel='bookmark' title='Permanent Link: Channels in Go'>Channels in Go</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li><li><a href='http://www.go-program.com/goroutines/' rel='bookmark' title='Permanent Link: Goroutines'>Goroutines</a></li></ol>]]></description>
			<content:encoded><![CDATA[<p>Concurrency issues</p>
<p>Many issues, of course, but Go tries to take care of them. Channel send and receive are atomic. The select statement is very carefully defined and implemented, etc.</p>
<p>But goroutines run in shared memory, communication networks can deadlock, multithreaded debuggers suck, and so on.</p>
<p>Go gives you the primitives</p>
<p>Don&#8217;t program the way you would in C or C++ or even Java.</p>
<p>Channels give you synchronization and communication both, and that makes them powerful but also easy to reason about if you use them well.<br />
The rule is:<br />
<script type="text/javascript"><!--
google_ad_client = "pub-9004887195759386";
/* Go programs text ads1 */
google_ad_slot = "3650915252";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
Do not communicate by sharing memory.<br />
Instead, share memory by communicating. The very act of communication guarantees synchronization!<br />
<script type="text/javascript"><!--
google_ad_client = "pub-9004887195759386";
/* Goprograms1 */
google_ad_slot = "8587802801";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script><br />
The model</p>
<p>For instance, use a channel to send data to a dedicated server goroutine. If only one goroutine at a time has a pointer to the data, there are no concurrency issues.<br />
This is the model we advocate for programming servers, at least. It&#8217;s the old &#8220;one thread per client&#8221; approach, generalized &#8211; and used by us since the 1980s. It works very well.</p>


<p>Related posts:<ol><li><a href='http://www.go-program.com/channels-in-go/' rel='bookmark' title='Permanent Link: Channels in Go'>Channels in Go</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li><li><a href='http://www.go-program.com/goroutines/' rel='bookmark' title='Permanent Link: Goroutines'>Goroutines</a></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/concurrency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiplexing</title>
		<link>http://www.go-program.com/multiplexing/</link>
		<comments>http://www.go-program.com/multiplexing/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 11:29:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=91</guid>
		<description><![CDATA[Channels are first-class values, which means they can be sent over channels. This property makes it easy to write a service multiplexer since the client can supply, along with its request, the channel on which to reply.

chanOfChans := make(chan chan int)
Or more typically
type Reply struct { &#8230; }
type Request struct {
arg1, arg2, arg3 some_type;
replyc chan [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p>Channels are first-class values, which means they can be sent over channels. This property makes it easy to write a service multiplexer since the client can supply, along with its request, the channel on which to reply.<br />
<!--adsense#image1--><br />
chanOfChans := make(chan chan int)<br />
Or more typically<br />
type Reply struct { &#8230; }<br />
type Request struct {<br />
arg1, arg2, arg3 some_type;<br />
replyc chan *Reply;<br />
}</p>
<p>Multiplexing server</p>
<p>type request struct {<br />
a, b int;<br />
replyc chan int;<br />
}<br />
type binOp func(a, b int) int<br />
func run(op binOp, req *request) {<br />
req.replyc <- op(req.a, req.b)<br />
}<br />
func server(op binOp, service chan *request) {<br />
for {<br />
req := <-service; // requests arrive here<br />
go run(op, req); // don't wait for op<br />
}<br />
}</p>
<p>Starting the server<br />
<!--adsense--><br />
Use the channel function pattern to create a channel to a new server:</p>
<p>func startServer(op binOp) chan *request {<br />
req := make(chan *request);<br />
go server(op, req);<br />
return req<br />
}<br />
var adderChan = startServer(<br />
func(a, b int) int { return a + b }<br />
)</p>
<p>The client</p>
<p>A similar example is worked in more detail in the tutorial, but here&#8217;s a variant:</p>
<p>func (r *request) String() string {<br />
return fmt.Sprintf(&#8221;%d+%d=%d&#8221;,<br />
r.a, r.b, <-r.replyc)<br />
}<br />
req1 := &#038;request{ 7, 8, make(chan int) };<br />
req2 := &#038;request{ 17, 18, make(chan int) };<br />
Requests ready; send them:<br />
adderChan <- req1;<br />
adderChan <- req2;<br />
Can retrieve results in any order; r.replyc demuxes:<br />
fmt.Println(req2, req1);</p>
<p>Teardown</p>
<p>In the mux example, the server runs forever. To tear it down cleanly, signal with a channel. This server has the same functionality but with a quit channel:</p>
<p>func server(op binOp, service chan *request,<br />
quit chan bool) {<br />
for {<br />
select {<br />
case req := <-service:<br />
go run(op, req); // don&#8217;t wait for it<br />
case <-quit:<br />
return;<br />
}<br />
}<br />
}</p>
<p>Starting the server</p>
<p>The rest of the code is mostly the same, with an extra channel:<br />
func startServer(op binOp) (service chan *request,<br />
quit chan bool) {<br />
service = make(chan *request);<br />
quit = make(chan bool);<br />
go server(op, service, quit);<br />
return service, quit;<br />
}<br />
var adderChan, quitChan := startServer(<br />
func(a, b int) int { return a + b }<br />
)</p>
<p>Teardown: the client</p>
<p>The client is unaffected until it&#8217;s ready to shut down the server:</p>
<p>req1 := &#038;request{7, 8, make(chan int)};<br />
req2 := &#038;request{17, 18, make(chan int)};<br />
adderChan <- req1;<br />
adderChan <- req2;<br />
fmt.Println(req2, req1);<br />
All done, signal server to exit:<br />
quitChan <- true;</p>
<p>Chaining</p>
<p>package main<br />
import (&#8221;flag&#8221;; &#8220;fmt&#8221;)<br />
var ngoroutine = flag.Int(&#8221;n&#8221;, 100000, &#8220;how many&#8221;)<br />
func f(left, right chan int) { left <- 1 + <-right }<br />
func main() {<br />
flag.Parse();<br />
leftmost := make(chan int);<br />
var left, right chan int = nil, leftmost;<br />
for i := 0; i < *ngoroutine; i++ {<br />
left, right = right, make(chan int);<br />
go f(left, right);<br />
}<br />
right <- 0; // bang!<br />
x := <-leftmost; // wait for completion<br />
fmt.Println(x); // 100000<br />
}</p>
<p>Example: Leaky bucket</p>
<p>Queue of shared, reusable buffers</p>
<p>var freeList = make(chan *Buffer, 100)<br />
var serverChan = make(chan *Buffer)<br />
func server() {<br />
for {<br />
b := <-serverChan; // wait for work<br />
process(b);<br />
ok := freeList <- b // reuse buffer if room<br />
}<br />
}<br />
func client() {<br />
for {<br />
b, ok := <-freeList; // grab one if available<br />
if !ok { b = new(Buffer) }<br />
load(b);<br />
serverChan <- b // send to server<br />
}<br />
}</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/multiplexing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Select</title>
		<link>http://www.go-program.com/select/</link>
		<comments>http://www.go-program.com/select/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 11:26:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=89</guid>
		<description><![CDATA[Select is a control structure in Go analogous to a communications switch statement. Each case must be a communication, either send or receive.

var c1, c2 chan int;
select {
case v := 


Related posts:<ol><li><a href='http://www.go-program.com/channels-in-go/' rel='bookmark' title='Permanent Link: Channels in Go'>Channels in Go</a></li><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li></ol>]]></description>
			<content:encoded><![CDATA[<p>Select is a control structure in Go analogous to a communications switch statement. Each case must be a communication, either send or receive.<br />
<!--adsense#image1--><br />
var c1, c2 chan int;<br />
select {<br />
case v := <-c1:<br />
fmt.Printf("received %d from c1\n", v)<br />
case v := <-c2:<br />
fmt.Printf("received %d from c2\n", v)<br />
}</p>
<p>Select executes one runnable case at random. If no case is runnable, it blocks until one is. A default clause is always runnable</p>
<p>Random bit generator<br />
<!--adsense--><br />
Silly but illustrative example.</p>
<p>c := make(chan int);<br />
go func() {<br />
for {<br />
fmt.Println(<-c)<br />
}<br />
}();<br />
for {<br />
select {<br />
case c <- 0: // no stmt, no fall through<br />
case c <- 1:<br />
}<br />
}<br />
Prints 0 1 1 0 0 1 1 1 0 1 &#8230;</p>


<p>Related posts:<ol><li><a href='http://www.go-program.com/channels-in-go/' rel='bookmark' title='Permanent Link: Channels in Go'>Channels in Go</a></li><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Channels in Go</title>
		<link>http://www.go-program.com/channels-in-go/</link>
		<comments>http://www.go-program.com/channels-in-go/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 11:10:09 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=86</guid>
		<description><![CDATA[Unless two goroutines can communicate, they can&#8217;t coordinate.
Go has a type called a channel that provides communication and synchronization capabilities.
It also has special control structures that build on channels to make concurrent programming easy.
The channel type

In its simplest form the type looks like this:
chan element_type
Given a value of this type, you can send and receive [...]


Related posts:<ol><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li><li><a href='http://www.go-program.com/select/' rel='bookmark' title='Permanent Link: Select'>Select</a></li></ol>]]></description>
			<content:encoded><![CDATA[<p>Unless two goroutines can communicate, they can&#8217;t coordinate.<br />
Go has a type called a channel that provides communication and synchronization capabilities.</p>
<p>It also has special control structures that build on channels to make concurrent programming easy.</p>
<p><strong>The channel type</strong><br />
<!--adsense--><br />
In its simplest form the type looks like this:</p>
<p>chan element_type</p>
<p>Given a value of this type, you can send and receive items of element_type. Channels are a reference type, which means if you assign one chan variable to another, both variables access the same channel. It also means you use make to allocate one:</p>
<p>var c = make(chan int)</p>
<p>The communication operator: <-</p>
<p>The arrow points in the direction of data flow.<br />
As a binary operator, <- sends to a channel:</p>
<p>var c chan int;<br />
c <- 1; // send 1 on c (flowing into c)</p>
<p>As a prefix unary operator, <- receives from a channel:<br />
v = <-c; // receive value from c, assign to v<br />
<-c; // receive value, throw it away<br />
i := <-c; // receive value, initialize i</p>
<p><strong>Semantics</strong></p>
<p>By default, communication is synchronous. </p>
<p>This means:<br />
1) A send operation on a channel blocks until a receiver is available for the same channel.<br />
2) A receive operation for a channel blocks until a sender is available for the same channel.<br />
Communication is therefore a form of synchronization: two goroutines exchanging data through a channel synchronize at the moment of communication.</p>
<p>Let&#8217;s pump some data</p>
<p>func pump(ch chan int) {<br />
for i := 0; ; i++ { ch <- i }<br />
}<br />
ch1 := make(chan int);<br />
go pump(ch1); // pump hangs; we run<br />
fmt.Println(<-ch1); // prints 0<br />
Now we start a looping receiver.<br />
func suck(ch chan int) {<br />
for { fmt.Println(<-ch) }<br />
}<br />
go suck(ch1); // tons of numbers appear<br />
You can still sneak in and grab a value:<br />
fmt.Println(<-ch); // Prints 314159</p>
<p><strong>Functions returning channels</strong></p>
<p>In the previous example, pump was like a generator spewing out values. But there was a lot of fuss allocating channels etc.<br />
Let&#8217;s package it up into a function returning the channel of values.</p>
<p>func pump() chan int {<br />
ch := make(chan int);<br />
go func() {<br />
for i := 0; ; i++ { ch <- i }<br />
}();<br />
return ch<br />
}<br />
stream := pump();<br />
fmt.Println(<-stream); // prints 0<br />
This is a very important idiom.</p>
<p><strong>Channel functions everywhere</strong></p>
<p>I am avoiding repeating famous examples you can find elsewhere. Here are a couple to look up:<br />
1) The prime sieve; in the language specification and also in the tutorial.<br />
2) Doug McIlroy&#8217;s power series work. </p>
<p>Range and channels</p>
<p>The range clause on for loops accepts a channel as an operand, in which case the for loops over the values received from the channel. </p>
<p>We rewrote pump; here&#8217;s the rewrite for suck, making it launch the goroutine as well:</p>
<p>func suck(ch chan int) {<br />
go func() {<br />
for v := range ch { fmt.Println(v) }<br />
}()<br />
}<br />
suck(pump()); // doesn&#8217;t block now</p>
<p>Closing a channel</p>
<p>What if we want to signal that a channel is done?<br />
We close it with a built-in function:<br />
close(ch)<br />
and test that state using closed():</p>
<p>if closed(ch) { fmt.Println(&#8221;done&#8221;) }</p>
<p>Once a channel is closed and every sent value has been received, every subsequent receive operation will recover a zero value.<br />
In practice, you rarely need close except in certain idiomatic situations.</p>
<p>When a channel closes</p>
<p>There are subtleties about races, so closed() succeeds only after you receive one zero value on the channel. The obvious loop isn&#8217;t right. To use closed() correctly you need to say:</p>
<p>for {<br />
v := <-ch;<br />
if closed(ch) { break }<br />
fmt.Println(v)<br />
}</p>
<p>But of course, the range clause does that for you.<br />
for v := range ch {<br />
fmt.Println(v)<br />
}</p>
<p>Iterators</p>
<p>Now we have all the pieces to write an iterator for a container. Here is the code for Vector:</p>
<p>// Iterate over all elements<br />
func (p *Vector) iterate(c chan Element) {<br />
for i, v := range p.a { // p.a is a slice<br />
c <- v<br />
}<br />
close(c); // signal no more values<br />
}<br />
// Channel iterator.<br />
func (p *Vector) Iter() chan Element {<br />
c := make(chan Element);<br />
go p.iterate(c);<br />
return c;<br />
}</p>
<p>Using the iterator</p>
<p>Now that Vector has an iterator, we can use it:</p>
<p>vec := new(vector.Vector);<br />
for i := 0; i < 100; i++ {<br />
vec.Push(i*i)<br />
}<br />
i := 0;<br />
for x := range vec.Iter() {<br />
fmt.Printf("vec[%d] is %d\n", i, x.(int));<br />
i++;<br />
}</p>
<p>Channel directionality</p>
<p>In its simplest form a channel variable is an unbuffered (synchronous) value that can be used to send and receive. </p>
<p>A channel type may be annotated to specify that it may only send or only receive:</p>
<p>var recv_only <-chan int;<br />
var send_only chan<- int;</p>
<p>Channel directionality (II)</p>
<p>All channels are created bidirectional, but we can assign them to directional channel variables.<br />
Useful for instance in functions, for (type) safety:<br />
func sink(ch <-chan int) {<br />
for { <-ch }<br />
}<br />
func source(ch chan<- int) {<br />
for { ch <- 1 }<br />
}<br />
var c = make(chan int); // bidirectional<br />
go source(c);<br />
go sink(c);</p>
<p><strong>Synchronous channels</strong></p>
<p>Synchronous channels are unbuffered. Sends do not complete until a receiver has accepted the value.</p>
<p>c := make(chan int);<br />
go func() {<br />
time.Sleep(60*1e9);<br />
x := <-c;<br />
fmt.Println("received", x);<br />
}();<br />
fmt.Println("sending", 10);<br />
c <- 10;<br />
fmt.Println("sent", 10);<br />
Output: sending 10 (happens immediately)<br />
sent 10 (60s later, these 2 lines appear)<br />
received 10</p>
<p><strong>Asynchronous channels</strong></p>
<p>A buffered, asynchronous channel can be created by giving make an argument, the number of elements in the buffer.<br />
c := make(chan int, 50);<br />
go func() {<br />
time.Sleep(60*1e9);<br />
x := <-c;<br />
fmt.Println("received", x);<br />
}();<br />
fmt.Println("sending", 10);<br />
c <- 10;<br />
fmt.Println("sent", 10);<br />
Output: sending 10 (happens immediately)<br />
sent 10 (now)<br />
received 10 (60s later)</p>
<p>Buffer is not part of the type</p>
<p>Note that the buffer's size, or even its existence, is not part of the channel's type, only of the value. This code is therefore legal, although dangerous:<br />
buf = make(chan int, 1);<br />
unbuf = make(chan int);<br />
buf = unbuf;<br />
unbuf = buf;</p>
<p>Buffering is a property of the value, not of the type.</p>
<p>Testing for communicability</p>
<p>Can a receive proceed without blocking? Need to find out and execute, or not, atomically.<br />
"Comma ok" to the rescue:<br />
v, ok = <-c; // ok=true if v received value</p>
<p>Can a send proceed without blocking? Need to find out and execute, or not, atomically. Use send as a boolean expression:<br />
ok := c <- v;<br />
or<br />
if c <- v { fmt.Println("sent value") }</p>
<p>Select</p>
<p>Select is a control structure in Go analogous to a communications switch statement. Each case must be a communication, either send or receive.</p>
<p>var c1, c2 chan int;<br />
select {<br />
case v := <-c1:<br />
fmt.Printf("received %d from c1\n", v)<br />
case v := <-c2:<br />
fmt.Printf("received %d from c2\n", v)<br />
}<br />
 <!--adsense#image1--><br />
Select executes one runnable case at random. If no case is runnable, it blocks until one is. A default clause is always runnable</p>


<p>Related posts:<ol><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li><li><a href='http://www.go-program.com/multiplexing/' rel='bookmark' title='Permanent Link: Multiplexing'>Multiplexing</a></li><li><a href='http://www.go-program.com/select/' rel='bookmark' title='Permanent Link: Select'>Select</a></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/channels-in-go/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Goroutines</title>
		<link>http://www.go-program.com/goroutines/</link>
		<comments>http://www.go-program.com/goroutines/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 11:05:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Basics]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=84</guid>
		<description><![CDATA[Terminology:

There are many terms for &#8220;things that run concurrently&#8221; &#8211; process, thread, coroutine, POSIX thread, NPTL thread, lightweight process, &#8230;,
But these all mean slightly different things. None means exactly how Go does concurrency. So we introduce a new term: goroutine.
Definition
A goroutine is a Go function or method executing concurrently in the same address space as [...]


Related posts:<ol><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li></ol>]]></description>
			<content:encoded><![CDATA[<p><strong>Terminology:</strong><br />
<!--adsense#image1--><br />
There are many terms for &#8220;things that run concurrently&#8221; &#8211; process, thread, coroutine, POSIX thread, NPTL thread, lightweight process, &#8230;,<br />
But these all mean slightly different things. None means exactly how Go does concurrency. So we introduce a new term: goroutine.</p>
<p><strong>Definition</strong></p>
<p>A goroutine is a Go function or method executing concurrently in the same address space as other goroutines.<br />
A running program consists of one or more goroutines. It&#8217;s not the same as a thread, coroutine, process, etc. It&#8217;s a goroutine.</p>
<p><strong>Starting a goroutine<br />
</strong><br />
Invoke a function or method and say go:</p>
<p>func IsReady(what string, minutes int64) {<br />
time.Sleep(minutes * 60*1e9);<br />
fmt.Println(what, &#8220;is ready&#8221;)<br />
}<br />
go IsReady(&#8221;tea&#8221;, 6);<br />
go IsReady(&#8221;coffee&#8221;, 2);<br />
fmt.Println(&#8221;I&#8217;m waiting&#8230;.&#8221;);<br />
Prints:<br />
I&#8217;m waiting&#8230;. (right away)<br />
coffee is ready (2 min later)<br />
tea is ready (6 min later)</p>
<p>Some simple facts</p>
<p>Goroutines are cheap.<br />
Goroutines exit by returning from their toplevel function, or just falling off the end. Or<br />
they can call runtime.Goexit(), although that&#8217;s rarely necessary.<br />
<!--adsense--><br />
Goroutines can run concurrently on different processors, sharing memory.<br />
You don&#8217;t have to worry about stack size.</p>
<p>Stacks</p>
<p>In gccgo, at least for now, goroutines are pthreads.</p>
<p>Stacks are big. We will fix this soon (our solution requires changes to gcc itself).<br />
In 6g, however, stacks are small (a few kB) and grow as needed. Thus in 6g, goroutines use little memory, you can have lots of them, and they can dynamically have huge stacks.</p>
<p><strong>Scheduling</strong></p>
<p>Goroutines are multiplexed as needed onto system threads. When a goroutine executes a blocking system call, no other goroutine is blocked.</p>
<p>We will do the same for CPU-bound goroutines at some point, but for now, if you want user-level parallelism you must set $GOMAXPROCS. or call runtime.GOMAXPROCS(n).</p>
<p>GOMAXPROCS tells the runtime scheduler how many non-syscall-blocked goroutines to run at once.</p>


<p>Related posts:<ol><li><a href='http://www.go-program.com/concurrency/' rel='bookmark' title='Permanent Link: Concurrency'>Concurrency</a></li></ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/goroutines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Go &#8211; Defer</title>
		<link>http://www.go-program.com/go-defer/</link>
		<comments>http://www.go-program.com/go-defer/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 16:58:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Defer]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=38</guid>
		<description><![CDATA[

The defer statement executes a function (or method) when the enclosing function returns. The arguments are evaluated at the point of the defer; the function call happens upon return.
func data(name string) string {
f := os.Open(name, os.O_RDONLY, 0);
defer f.Close();
contents := io.ReadAll(f);
return contents;
}
Useful for closing fds, unlocking mutexes, etc.
Tracing with defer
func trace(s string) { Print(&#8221;entering:&#8221;, s); }
func [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p><!--adsense--><br />
<!--adsense#image1--></p>
<p>The defer statement executes a function (or method) when the enclosing function returns. The arguments are evaluated at the point of the defer; the function call happens upon return.</p>
<p>func data(name string) string {</p>
<p>f := os.Open(name, os.O_RDONLY, 0);</p>
<p>defer f.Close();</p>
<p>contents := io.ReadAll(f);</p>
<p>return contents;</p>
<p>}</p>
<p>Useful for closing fds, unlocking mutexes, etc.</p>
<p>Tracing with defer</p>
<p>func trace(s string) { Print(&#8221;entering:&#8221;, s); }</p>
<p>func untrace(s string) { Print(&#8221;leaving:&#8221;, s); }</p>
<p>func a() {</p>
<p>trace(&#8221;a&#8221;);</p>
<p>defer untrace(&#8221;a&#8221;);</p>
<p>Print(&#8221;in a&#8221;)</p>
<p>}</p>
<p>func b() {</p>
<p>trace(&#8221;b&#8221;);</p>
<p>defer untrace(&#8221;b&#8221;);</p>
<p>Print(&#8221;in b&#8221;);</p>
<p>a()</p>
<p>}</p>
<p>func main() { b() }</p>
<p>Args evaluate now, defer later</p>
<p>func trace(s string) string {</p>
<p>Print(&#8221;entering:&#8221;, s);</p>
<p>return s</p>
<p>}</p>
<p>func un(s string) {</p>
<p>Print(&#8221;leaving:&#8221;, s)</p>
<p>}</p>
<p>func a() {</p>
<p>defer un(trace(&#8221;a&#8221;));</p>
<p>Print(&#8221;in a&#8221;)</p>
<p>}</p>
<p>func b() {</p>
<p>defer un(trace(&#8221;b&#8221;));</p>
<p>Print(&#8221;in b&#8221;);</p>
<p>a()</p>
<p>}</p>
<p>func main() { b() }</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/go-defer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Go &#8211; Functions</title>
		<link>http://www.go-program.com/go-functions/</link>
		<comments>http://www.go-program.com/go-functions/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 16:38:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Functions]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=36</guid>
		<description><![CDATA[

Functions
Functions are introduced by the func keyword.
Return type, if any, comes after parameters. The return does as you expect.
func square(f float) float { return f*f }
A function can return multiple values. If so, the return types are a parenthesized list.
func MySqrt(f float) (float, bool) {
if f &#62;= 0 { return math.Sqrt(f), true }
return 0, false
}
Functions [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p><!--adsense--><br />
<!--adsense#image1--></p>
<p>Functions</p>
<p>Functions are introduced by the func keyword.</p>
<p>Return type, if any, comes after parameters. The return does as you expect.</p>
<p>func square(f float) float { return f*f }</p>
<p>A function can return multiple values. If so, the return types are a parenthesized list.</p>
<p>func MySqrt(f float) (float, bool) {</p>
<p>if f &gt;= 0 { return math.Sqrt(f), true }</p>
<p>return 0, false</p>
<p>}</p>
<p>Functions with result variables</p>
<p>The result &#8220;parameters&#8221; are actual variables you can use if you name them.</p>
<p>func MySqrt(f float) (v float, ok bool) {</p>
<p>if f &gt;= 0 { v,ok = math.Sqrt(f),true }</p>
<p>else { v,ok = 0,false }</p>
<p>return v,ok</p>
<p>}</p>
<p>The result variables are initialized to &#8220;zero&#8221;</p>
<p>(0,0.0, false etc. according to type; more in a sec).</p>
<p>func MySqrt(f float) (v float, ok bool) {</p>
<p>if f &gt;= 0 { v,ok = math.Sqrt(f),true }</p>
<p>return v,ok</p>
<p>}</p>
<p>The empty return</p>
<p>Finally, a return with no expressions returns the existing value of the result variables. Two more versions of MySqrt:</p>
<p>func MySqrt(f float) (v float, ok bool) {</p>
<p>if f &gt;= 0 { v,ok = math.Sqrt(f),true }</p>
<p>return // must be explicit</p>
<p>}</p>
<p>func MySqrt(f float) (v float, ok bool) {</p>
<p>if f &lt; 0 { return } // error case</p>
<p>return math.Sqrt(f),true</p>
<p>}</p>
<p>Function literals</p>
<p>As in C, functions can&#8217;t be declared inside functions -but function literals can be assigned to variables.</p>
<p>func f() {</p>
<p>for i := 0; i &lt; 10; i++ {</p>
<p>g := func(i int) { fmt.Printf(&#8221;%d&#8221;,i) };</p>
<p>g(i);</p>
<p>}</p>
<p>}</p>
<p>Function literals are closures</p>
<p>Function literals are indeed closures.</p>
<p>func adder() (func(int) int) {</p>
<p>var x int;</p>
<p>return func(delta int) int {</p>
<p>x += delta;</p>
<p>return x</p>
<p>}</p>
<p>}</p>
<p>var f = adder();</p>
<p>fmt.Print(f(1));</p>
<p>fmt.Print(f(20));</p>
<p>fmt.Print(f(300));</p>
<p>Prints 1 21 321 &#8211; accumulating in f&#8217;s x</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/go-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GO Programming Language Declarations</title>
		<link>http://www.go-program.com/go-language-declarations/</link>
		<comments>http://www.go-program.com/go-language-declarations/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 16:34:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Declarations]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=33</guid>
		<description><![CDATA[
Declarations
Declarations are introduced by a keyword
var
const
type
func
and look reversed compared to C:
var i int
const PI = 22./7.
type Point struct { x, y int }
func sum(a, b int) int { return a + b }
Why are they reversed? Earlier example:
var p, q *int
Also functions read better and are consistent with other declarations.
Var
Variable declarations are introduced by var.
They [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p><!--adsense--></p>
<p>Declarations<br />
Declarations are introduced by a keyword<br />
var<br />
const<br />
type<br />
func</p>
<p>and look reversed compared to C:</p>
<p>var i int<br />
const PI = 22./7.<br />
type Point struct { x, y int }<br />
func sum(a, b int) int { return a + b }</p>
<p>Why are they reversed? Earlier example:<br />
var p, q *int<br />
Also functions read better and are consistent with other declarations.</p>
<p>Var</p>
<p>Variable declarations are introduced by var.<br />
They may have a type or an initialization expression; one or both must be present. Initializers must match variables (and types!).</p>
<p>var i int<br />
var j = 365.245<br />
var k int = 0<br />
var l, m uint64 = 1, 2<br />
var billion int64 = 1e9 // float constant!<br />
var inter, floater, stringer = 1, 2.0, &#8220;hi&#8221;</p>
<p>Distributing var<br />
<!--adsense#image1--><br />
Annoying to type var all the time. Group with parens! Need semicolons as separators.</p>
<p>var (<br />
i int;<br />
j = 356.245;<br />
k int = 0;<br />
l, m uint64 = 1, 2;<br />
billion int64 = 1e9;<br />
inter, floater, stringer = 1, 2.0, &#8220;hi&#8221;<br />
)</p>
<p>Applies to const, type, var</p>
<p>The := &#8220;short declaration&#8221;</p>
<p>Within functions (only), declarations of the form</p>
<p>var v = value<br />
can be shortened to<br />
v := value</p>
<p>(Another reason for the name/type reversal.)<br />
The type is that of the value (for ideal numbers, get<br />
int or float, accordingly.)</p>
<p>a, b, c, d := 1, 2.0, &#8220;three&#8221;, FOUR</p>
<p>These are used a lot and are available in places such as for loop initializers.</p>
<p>Const</p>
<p>Constant declarations are introduced by const.<br />
They must have a &#8220;constant expression&#8221;, evaluated at compile time, as initializer and may have an optional type specifier.</p>
<p>const Pi = 22./7.<br />
const AccuratePi float64 = 355./113<br />
const beef, two, parsnip = &#8220;meat&#8221;, 2, &#8220;veg&#8221;<br />
const (<br />
Monday, Tuesday, Wednesday = 1, 2, 3;<br />
Thursday, Friday, Saturday = 4, 5, 6;<br />
)</p>
<p>Iota</p>
<p>Constant declarations can use the counter iota, which starts at 0 in each const block and increments at each semicolon.</p>
<p>const (<br />
Monday = iota; // 0<br />
Tuesday = iota; // 1<br />
)</p>
<p>Shorthand: Previous type and expressions repeat.<br />
const (<br />
loc0, bit0 uint32 = iota, 1&amp;lt;<br />
loc1, bit1; // 1, 2<br />
loc2, bit2; // 2, 4<br />
)</p>
<p>Type</p>
<p>Type declarations are introduced by type.<br />
We&#8217;ll learn more about types later but here are some examples:</p>
<p>type Point struct {<br />
x, y, z float;<br />
name string<br />
}</p>
<p>type Operator func(a, b int) int<br />
type ArrayOfIntPointers []*int<br />
We&#8217;ll come back to functions a little later.</p>
<p>New</p>
<p>The new() operator allocates memory. Syntax is like a function call, with type as argument, similar to C++. Returns a pointer to the allocated object.</p>
<p>var p *Point = new(Point)<br />
v := new(int) // v has type *int</p>
<p>Later we&#8217;ll see how to build arrays and such.<br />
There is no delete or free; Go has garbage collection.</p>
<p>Assignment<br />
Assignment is easy and familiar:<br />
a = b<br />
But multiple assignment works too:<br />
x, y, z = f1(), f2(), f3()<br />
a, b = b, a</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/go-language-declarations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Go Language Videos</title>
		<link>http://www.go-program.com/go-language-videos/</link>
		<comments>http://www.go-program.com/go-language-videos/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 16:20:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Videos]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=28</guid>
		<description><![CDATA[
Go Programming Language Promo 


The Go Programming Language



No related posts.


No related posts.]]></description>
			<content:encoded><![CDATA[<p><!--adsense--></p>
<p><strong>Go Programming Language Promo </strong></p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="295" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/wwoWei-GAPo&amp;hl=en_US&amp;fs=1" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="295" src="http://www.youtube.com/v/wwoWei-GAPo&amp;hl=en_US&amp;fs=1" allowscriptaccess="always" allowfullscreen="true"></embed></object><br />
<!--adsense#image1--></p>
<p>The Go Programming Language<br />
<object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/rKnDgT73v8s&#038;hl=en_US&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/rKnDgT73v8s&#038;hl=en_US&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object></p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/go-language-videos/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Go Language Expressions</title>
		<link>http://www.go-program.com/go-language-expressions/</link>
		<comments>http://www.go-program.com/go-language-expressions/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 15:13:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Expressions]]></category>

		<guid isPermaLink="false">http://www.go-program.com/?p=19</guid>
		<description><![CDATA[
Expressions
Mostly C-like operators.
Binary operators:




Prec


operators


comments




6


* / % &#60;&#60; &#62;&#62; &#38; &#38;^

&#38;^   is &#8220;bit clear&#8221;



5


+ &#8211; &#124; ^


^ is &#8220;xor&#8221;




4


== != &#60; &#60;= &#62; &#62;=







3


&#60;-


communication




2


&#38;&#38;







1


&#124;&#124;








Operators that are also unary: &#38; ! * + &#8211; ^ &#60;-
Unary ^ is complement.

Go vs. C expressions
Surprises for the C programmer:

fewer precedence levels (should be easy)
^ instead of ~ (it&#8217;s [...]


No related posts.]]></description>
			<content:encoded><![CDATA[<p><!--adsense--></p>
<p>Expressions</p>
<p>Mostly C-like operators.</p>
<p>Binary operators:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="119" valign="top">
<p align="center">Prec</p>
</td>
<td width="212" valign="top">
<p align="center">operators</p>
</td>
<td width="162" valign="top">
<p align="center">comments</p>
</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">6</p>
</td>
<td width="212" valign="top">
<p align="center">* / % &lt;&lt; &gt;&gt; &amp; &amp;^</p>
</td>
<td width="162" valign="top">&amp;^   is &#8220;bit clear&#8221;</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">5</p>
</td>
<td width="212" valign="top">
<p align="center">+ &#8211; | ^</p>
</td>
<td width="162" valign="top">
<p align="center">^ is &#8220;xor&#8221;</p>
</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">4</p>
</td>
<td width="212" valign="top">
<p align="center">== != &lt; &lt;= &gt; &gt;=</p>
</td>
<td width="162" valign="top">
<p align="center">
</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">3</p>
</td>
<td width="212" valign="top">
<p align="center">&lt;-</p>
</td>
<td width="162" valign="top">
<p align="center">communication</p>
</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">2</p>
</td>
<td width="212" valign="top">
<p align="center">&amp;&amp;</p>
</td>
<td width="162" valign="top">
<p align="center">
</td>
</tr>
<tr>
<td width="119" valign="top">
<p align="center">1</p>
</td>
<td width="212" valign="top">
<p align="center">||</p>
</td>
<td width="162" valign="top">
<p align="center">
</td>
</tr>
</tbody>
</table>
<ul>
<li>Operators that are also unary: &amp; ! * + &#8211; ^ &lt;-</li>
<li>Unary ^ is complement.</li>
</ul>
<p style="text-align: center;">Go vs. C expressions</p>
<p>Surprises for the C programmer:<br />
<!--adsense#image1--><br />
fewer precedence levels (should be easy)</p>
<p>^ instead of ~ (it&#8217;s binary &#8220;exclusive or&#8221; made unary)</p>
<p>++ and &#8212; are not expression operators</p>
<p>(x++ is a statement, not an expression;</p>
<p>*p++ is (*p)++ not *(p++))</p>
<p>&amp;^ is new; handy in constant expressions</p>
<p>&lt;&lt; &gt;&gt; etc. require an unsigned shift count</p>
<p>Non-surprises:</p>
<p>assignment ops work as expected: += &lt;&lt;= &amp;^= etc.</p>
<p>expressions generally look the same (indexing,</p>
<p>function call, etc.)</p>
<p>Examples</p>
<p>+x</p>
<p>23 + 3*x[i]</p>
<p>x &lt;= f()</p>
<p>^a &gt;&gt; b</p>
<p>f() || g()</p>
<p>x == y + 1 &amp;&amp; &lt;-chan_ptr &gt; 0</p>
<p>x &amp;^ 7 // x with the low 3 bits cleared</p>
<p>fmt.Printf(&#8221;%5.2g\n&#8221;, 2*math.Sin(PI/8))</p>
<p>&#8220;hello&#8221; &#8220;, &#8221; &#8220;there&#8221; // lexical cat</p>
<p>&#8220;hello, &#8221; + str // dynamic cat</p>
<p>Numeric conversions</p>
<p>Converting a numeric value from one type to another is a conversion, with syntax like a function call:</p>
<p>uint8(int_var)        // truncate to size</p>
<p>int(float_var)        // truncate fraction</p>
<p>float64(int_var)    // convert to float</p>
<p>Also some conversions to string:</p>
<p>string(0&#215;1234)     // == &#8220;\u1234&#8243;</p>
<p>string(array_of_bytes)   // bytes -&gt; bytes</p>
<p>string(array_of_ints)      // ints -&gt; Unicode/UTF-8</p>
<p>Constants</p>
<p>Numeric constants are &#8220;ideal numbers&#8221;: no size or sign, hence no l or u or ul endings.</p>
<p>Example:</p>
<p>077 // octal</p>
<p>0xFEEDBEEEEEEEEEEEEEEEEEEEEF // hexadecimal</p>
<p>1 &lt;&lt; 100</p>
<p>There are integer and floating-point ideal numbers; syntax of literal determines type:</p>
<p>Example:</p>
<p>1.234e5</p>
<p>1e2 // floating-point</p>
<p>100 // integer</p>
<p>Constant Expressions</p>
<p>Floating point and integer constants can be combined at will, with the type of the resulting expression determined by the type of the constants.</p>
<p>The operations themselves also depend on the type.</p>
<p>2*3.14        // floating point: 6.28</p>
<p>3./2    // floating point: 1.5</p>
<p>3/2     // integer: 1</p>
<p>// high precision:</p>
<p>const Ln2</p>
<p>= 0.693147180559945309417232121458\</p>
<p>176568075500134360255254120680009</p>
<p>const Log2E</p>
<p>= 1/Ln2       // accurate reciprocal</p>
<p>Representation is &#8220;big enough&#8221; (1024 bits now).</p>
<p>Consequences of ideal numbers</p>
<p>The language permits the use of constants without explicit conversion if the value can be represented</p>
<p>var million int = 1e6      / float constant</p>
<p>math.Sin(1)</p>
<p>Constants must be representable in their type.</p>
<p>Example:</p>
<p>^0 is -1 which is not in range 0-255.</p>
<p>uint8(^0)     / bad: -1 can&#8217;t be represented</p>
<p>^uint8(0)     // OK</p>
<p>uint8(350)   // bad: 350 can&#8217;t be represented</p>
<p>uint8(35.0)  // OK: 35</p>
<p>uint8(3.5)     // bad: 3.5 can&#8217;t be represented</p>


<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://www.go-program.com/go-language-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
