TRANSILVANIA University of Bra sov [600774]
TRANSILVANIA University of Bra sov
Faculty of Mathematics and Informatics
Master: Internet Technologies
DISSERTATION
Author: Teodora Angelica Dunca
Scientic coordinator: Prof. univ. dr. Ernest Scheiber
BRAS OV
2012
TRANSILVANIA University of Bra sov
Faculty of Mathematics and Informatics
Master: Internet Technologies
DISTRIBUTED PROGRAMMING
IN GO
Author: Teodora Angelica Dunca
Scientic coordinator: Prof. univ. dr. Ernest Scheiber
BRAS OV
2012
Content
1 The Go programming language 3
1.1 Installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Editing programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.1 First programs in Go . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.2 Compiling and running . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Notions of syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.1 Commentary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3.2 Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.3.3 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.4 Control structures . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.3.5 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2 Concurrent programming in Go 16
2.1 Goroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.2 Channels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.3 WaitGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.4 Select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.5 Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6 Once . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3 Network programming with Go 22
3.1 Remote Procedure Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.1.1 HTTP RPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.1.2 TCP RPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1.3 JSON RPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.2 Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
3.2.1 TCP Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Bibliography 78
1
Introduction
"Go is not meant to innovate programming theory.
It's meant to innovate programming practice."
Samuel Tesla
The Go programming language is an expressive, compiled and concurrent program-
ming language developed by Google Inc. . Go language is an open source programming
environment that makes it easy to build simple, productive and ecient project.
The programming language Go is like C++ and Java, but its unusual properties make
programs more ecient, it was designed to reduce the size of code and reduce compilation
time. A transcript of the programs written in Java or C++ in Go, would make the program
acceptable, but if written directly in Go would be a successful and dierent software.
This paper describes how to work with distributed programming in Go and has three
main chapters: The Go programming language ,Concurrent programming in Go and Net-
work programming with Go . In these chapters are presented lexical items and syntax of
the Go programming language (Chapter 1), notions necessary for the concurrent programs
(Chapter 2), and the last chapter shows how to work in network programming with Go
programming language.
The Go programming language is object oriented but does not use objects, such a
program written in Go is a package that import necesary functions from other packages,
packages imported must to be used. In concurrent programming a process is an execution
of a program segment. Advantages of concurrent programming is that multiple programs
can be executed simultaneously and the programs have potentially by interacting with
each other.
The primitives for concurrency present in Go provide an elegant and distinct means
of structuring concurrent software. These concepts are goroutines and channels. Go
channels synchronize and communicate; the sending goroutine waits until the receiving
goroutine is ready to accept the communication.
Go uses several OS threads to do parallel computations and channels. Channels may
be synchronous, or asynchronous. Network Programming is essentially identied client-
server programming, is for development of applications that communicate with other
applications in the networking. In the Go programming language remote procedure call
(RPC) is unique, being dierent from the RPC used in other programming languages.
With the explained examples I tried to emphasize the simplicity of editing code and
how easy is to use this language. Also, Go is a new programming language, what is
waiting to be discovered, because it has a lot of new ideas, is innovative, easy and free.
2
Chapter 1
The Go programming language
The Go programming language is an expressive, compiled and concurrent program-
ming language developed by Google Inc. . Go language is an open source programming
environment that makes it easy to build simple, productive and ecient project. The
rst design of Go was done in September 2007 by Robert Griesemer, Rob Pike, and Ken
Thompson, but it was ocially announced in November 2009. The GO programming
language is available for Linux, FreeBSD, Mac OS X and for Windows (since 2011). Go
is in
uenced by programming languages C, Newsqueak, Pascal, Pyton and others.
At rst, Go was not considered to be ready for real production environments. In May
2010, Rob Pike stated publicly that Go is being used "for real stu" at Google. Go is
a very young programming language and is it not revolutionary, it is a good way for
evolution.
J org Walter has written a detailed and positive review of the Go programming lan-
guage. "And as a nal note, I have seen a fair amount of criticism of Go on the internet,
which I cannot ignore, so here it goes: Most of these people didn't actually look at it. Go
is dierent, even though it still looks kinda-C. It isn't. It's not C++, nor Objective C,
and it doesn't try to be! So stop saying 'Who needs Go when we have C++/Objective
C?' already. Check out how Go tries to solve the same problems in a radically dierent
way." [8]
This language was designed to reduce the size of code written in other programming
languages (C, C++, Java), and reduce compilation time. Dynamic languages (Python,
JavaScript) x these problems (no more types, no more compiler) but introduce others like
errors at run time that should be caught statically and no compilation means slow code.
This language was designed because in 10 years it wasn't designed other programming
language. [9]
The Go programming language has been around for almost 3 years and was expe-
rimental when it was released, but because it's easy to learn it will have succed in IT
world.
1.1 Installing
Go is an open source project and is written in C, so to built it you need to install:
3
the GCC2 compiler;
the standard libraries of C;
the Bison generator;
make;
awk;
the text editor ed.
The instalation of the program is in the command line. On the website of the
programming language (http://golang.org/doc/install.html) you nd all versions of the
installation for both platforms OS X and for Linux. For the OS X platform is not
ready but you can use it. For more information go to (http://code.google.com/p/go-
wiki/wiki/WindowsSupport) and (http://code.google.com/p/go/wiki/WindowsPort). For
easier code editing was developed a tool called Gocode. How to do that you nd on
(https://github.com/nsf/gocode). If the program installation is successful, it nishes by
printing output:
ALL TESTS PASSED
Installed Go for linux/amd64 in /home/you/go.
Installed commands in /home/you/go/bin.
*** You need to add /home/you/go/bin to your $PATH. ***
The compiler is 6g.
where the details on the last few lines re
ect the operating system, architecture, and root
directory used during the install. Depending of the computer conguration, will return
compiler version used.
To renew the installed version of GO, software updates will use the following com-
mands:
cd go/src
hg pull
hg update release
./all.bash
For a better use of program commands is recommended to set the PATH system
variable, with the path where is installed GO. Also, you have to set these variables in
your prole:
GOROOT=$HOME/GO
GOARCH=386
GOOS=LINUX
where, GOROOT represent the path where the distribution has been installed, GOARCH
represent the type of used architecture, and GOOS represent the operating system.
4
1.2 Editing programs
Go programs use the UTF-8 encoding and have the extension .go. Editing of programs
is made by text editor, the most popular may even have support for Go color syntax
highlighting and automatic indentation.
In Go to run a program with the name rst.go will follow the steps:
compiling program: 6g rst.go ;
realization a connection to the compiled le: 6l rst.6 ;
running program: ./6.out
Where the compiler version used is number 6.
1.2.1 First programs in Go
A program in the Go programming language looks like:
Example 1.2.1
1 package main
3 import "fmt"
5 func main ( )f
6 fmt . P r i n t f ( " I j u s t want to say hy ! ! ! nn" )
7g
I just want to say hy!!!
This program is saved name rstand extension .go: (rst.go ).
The rst statement in a Go source is:
1package packagename
where packagename is the package's default name for imports, all les in a package
must use the same name. In our example the package name is main . Other packages can
be imported to use another functions. This program import the package fmt, because
uses the function Printf . A reason why Go programs are build so quickly is because we
do not need to compile any other packages, rst.go uses standard library packages.
The Go programming language is object oriented but does not use objects, such a
program written in Go is a package that import necesary functions from other packages,
packages imported must to be used.
Is not a problem if in Go the separator ";" is not put at the end of the instructions,
because Go is automatically inserted after each line. But it is sometimes necessary to use
it, for example declaring several variables, etc..
5
It is mandatory to leave one empty line between the package name, import statement
and functions of the program. If this feature is not observed, it will signal to the compiler.
The next program in the Go programming language is about adding two numbers.
This program is saved name addand extension .go: (add.go ). We write the two numbers
and after compilation the result is displayed.
Example 1.2.2
1package main
3import "fmt"
5func main ()f
6 var e r r e r r o r
7 var M, N, sum f l o a t 6 4
9 p r i n t ( " F i r s t number : " )
10 , e r r = fmt . Scanln(& M)
11 i fe r r != n i lf
12 fmt . Println ( " Error : " , e r r )
13g
15 p r i n t ( "Second number : " )
16 , e r r = fmt . Scanln(&N)
17 i fe r r != n i lf
18 fmt . Println ( " Error : " , e r r )
19g
21 sum = M + N;
22 fmt . Println ( "Sum: " , sum)
23g
The third program in the Go programming language makes convert from degrees
Celsius to degrees Fahrenheit and vice versa. This program is saved name conversion and
extension .go: (conversion.go ). We write the two degrees and after compilation the result
is displayed.
Example 1.2.3
1package main
3import "fmt"
5func main ()f
6 var e r r e r r o r
7 var Sens int
9 p r i n t ( " Sens : " )
10 , e r r = fmt . Scanln(&Sens )
11 i fe r r != n i lf
12 fmt . Println ( " Error : " , e r r )
13g
15 var G f l o a t 6 4
16 p r i n t ( "Grade : " )
17 , e r r = fmt . Scanln(&G)
18 i fe r r != n i lf
19 fmt . Println ( " Error : " , e r r )
20g
6
22 i fSens == 0f
23 fmt . Println ( "C2F =" , 1.8 G+32)
24gelsef
25 i fSens == 1f
26 fmt . Println ( "F2C =" ,(G 32)/1.8)
27 gelsef
28 fmt . Println ( " You ' re a s t r a n g e r ! " )
29 g
30 g
31g
This program computes the greatest common divisor of two numbers. This program
is saved name cmmdc and extension .go: (cmmdc.go ). We write the two numbers and
after compilation the result is displayed.
Example 1.2.4
1package main
3import "fmt" ;
5func main ()f
7 var e r r e r r o r
8 var M, N int
10 p r i n t ( "M: " )
11 , e r r = fmt . Scanln(& M)
12 i fe r r != n i lf
13 fmt . Println ( " Error : " , e r r )
14g
16 p r i n t ( "N: " )
17 , e r r = fmt . Scanln(&N)
18 i fe r r != n i lf
19 fmt . Println ( " Error : " , e r r )
20g
22 var C int
23 for R:=1; R!=0;f
24 C = N;
25 R = M % N;
26 M = N;
27 N = R;
28g
30 fmt . Println ( "Cmmdc: " , C)
31g
The next program will display the conversion between the USA, EUR and RON.
Introduce the type of the conversion and the value and after compilation the result is
displayed. This program is saved name Convmoney and extension .go: (Convmoney.go ).
Example 1.2.5
1package main
3import "fmt"
5func main ()f
6 var e r r e r r o r
7
7 var val , do l a r i , euro f l o a t 6 4
8 var from f l o a t 6 4
10 p r i n t ( "From : " )
11 , e r r = fmt . Scanln(&from )
12 i fe r r != n i lf
13 fmt . Println ( " Error : " , e r r )
14g
16 p r i n t ( "Value : " )
17 , e r r = fmt . Scanln(&val )
18 i fe r r != n i lf
19 fmt . Println ( " Error : " , e r r )
20g
22 d o l a r i = 3 . 5 5 7 3 ;
23 euro = 4 . 4 4 4 1 ;
25 i ffrom == 10f
26 fmt . Println ( "RON = >EURO =" , val / euro )
27g
29 i ffrom == 11f
30 fmt . Println ( "RON = >USD =" , val / d o l a r i )
31g
33 i ffrom == 20f
34 fmt . Println ( "EURO = >RON =" , valeuro )
35g
37 i ffrom == 22f
38 fmt . Println ( "USD = >RON =" , vald o l a r i )
39g
41 i ffrom == 30f
42 fmt . Println ( "EURO = >USD =" , valeuro / d o l a r i )
43g
45 i ffrom == 33f
46 fmt . Println ( "USD = >EURO =" , vald o l a r i / euro )
47g
48g
The last program will determine the European zodiac. This program is saved name
zodiac and extension .go: (zodiac.go ).
Example 1.2.6
1package main
3import "fmt"
5func main ()f
6 var e r r e r r o r
7 var month , day int
9 p r i n t ( "Day : " )
10 , e r r = fmt . Scanln(&day )
11 i fe r r != n i lf
12 fmt . Println ( " Error : " , e r r )
13g
15 p r i n t ( "Month : " )
16 , e r r = fmt . Scanln(&month)
17 i fe r r != n i lf
8
18 fmt . Println ( " Error : " , e r r )
19g
21 i f( ( month == 12 && day >= 22 && day <= 31)
22 jj(month == 1 && day >= 1 && day <= 19))f
23 fmt . Println ( " Capricorn " )
24gelsef
25 i f( ( month == 1 && day >= 20 && day <= 31)
26 jj(month == 2 && day >= 1 && day <= 17))f
27 fmt . Println ( " Aquarius " )
28gelsef
29 i f( ( month == 2 && day >= 18 && day <= 29)
30 jj(month == 3 && day >= 1 && day <= 19))f
31 fmt . Println ( " P i s c e s " )
32gelsef
33 i f( ( month == 3 && day >= 20 && day <= 31)
34 jj(month == 4 && day >= 1 && day <= 19))f
35 fmt . Println ( " Aries " )
36gelsef
37 i f( ( month == 4 && day >= 20 && day <= 30)
38 jj(month == 5 && day >= 1 && day <= 20))f
39 fmt . Println ( " Bull " )
40 gelsef
41 i f( ( month == 5 && day >= 21 && day <= 31)
42 jj(month == 6 && day >= 1 && day <= 20))f
43 fmt . Println ( "Gemini" )
44gelsef
45 i f( ( month == 6 && day >= 21 && day <= 30)
46 jj(month == 7 && day >= 1 && day <= 22))f
47 fmt . Println ( "Cancer" )
48gelsef
49 i f( ( month == 7 && day >= 23 && day <= 31)
50 jj(month == 8 && day >= 1 && day <= 22))f
51 fmt . Println ( "Leo" )
52gelsef
53 i f( ( month == 8 && day >= 23 && day <= 31)
54 jj(month == 9 && day >= 1 && day <= 22))f
55 fmt . Println ( " Virgin " )
56gelsef
57 i f( ( month == 9 && day >= 23 && day <= 30)
58 jj(month == 10 && day >= 1 && day <= 22))f
59 fmt . Println ( " Libra " )
60gelsef
61 i f( ( month == 10 && day >= 23 && day <= 31)
62 jj(month == 11 && day >= 1 && day <= 21))f
63 fmt . Println ( " Scorpio " )
64gelsef
65 i f( ( month == 11 && day >= 22 && day <= 30)
66 jj(month == 12 && day >= 1 && day <= 21))f
67 fmt . Println ( " S a g i t t a r i u s " )
68gelsef
69 fmt . Println ( " I l l e g a l date " )
70 g
71 g
72 g
73 g
74 g
75 g
76 g
77 g
78 g
79 g
80g
81g
82g
9
1.2.2 Compiling and running
The Go compiler Gccgo is a compiler that is based on compiler GCC (GNU Compiler
Collection), compiler used and for languages C, C + + and Java.
If our architecture is i386 we have the following program names:
8g- compiles .go programs;
8l- produce binaries;
8c- code generation bug;
8a- is an assembler.
for amd64 these binaries will be named dierently: 6g, 6l, 6c, 6a.
Compiling and running a go program takes three steps:
run '6g rst.go '
– compiles rst.go programs to go object code, rst.6.
run '6l rst.6 '
– it makes a linker which takes go object code and produces binaries, 6.out.
run '6.out '
– by running this le will display the message, "I just want to say hy!!!" .
Another way to compile and run a program is using the command gomake .
1.3 Notions of syntax
The programming language Go is like C++ and Java, but its unusual properties make
programs more ecient. A transcript of the programs written in Java or C++ in Go,
would make the program acceptable, but if written directly in Go would be a successful
and dierent software. It is very important and recommended as well to understand
properties and expressions, so that programs to be easily understood by developers of Go.
1.3.1 Commentary
Comments in Go are the same like in C and C++:
/* */ { block comments like in C style (block comments appear mostly as package
comments);
/* this is
a comment */
=={ line comments like in C++ style (line comments are the norm).
// this is a comment
10
1.3.2 Syntax
The syntax is almost the same like in C or C++, but in Go is more strong. It will
use the varkeyword to declare variables, const keyword to declare constants and the type
keyword for user-dened types. To observe the dierent ways of declaring the pointers,
the vectors, and how is a variable initialized.
Constants
Constants in Go are created at compile time and can only be numbers, strings or
booleans. In Go constants with value numbers are created by using the iotaenumerator.
1const one = 1
We can group the constants by using round brackets:
1const (
2January = i o t a ; // 0
3February = i o t a ; // 1
4)
Variables
Variables can be initialized just like constants but the initializer can be a general
expression computed at run time.
1var x int
2var y , zint
3var n [ ] int
or group of variables:
1var (
2 xint
3 y , zint
4 n [ ] int
5)
Note that using the separator ";" to separate variables.
Another way to declare and initialize variables is by using the operator ":=", so:
var v = value;
can be written like:
v := value
To initialize global variables you can use one of the two methods provided:
initializing variables when are declared;
use function init() for each variable.
11
Dened types
Dened types are declared using a construction like:
1type Equation s t r u c t f
2 x , y , z float ;
3 name s t r i n g
4g
1.3.3 Operators
In Go are four categories of operators:
binary operators;
unary operators;
operator new;
assignment operators.
Binary operators
In Go can use the following binary operators:
Previous Operators
6 *=% &
5 + -j^
4 == ! = <>
3 <{
2 &&
1jj
Binary^operator is used for operation "or exclusively" ( XOR ).
Unary operators
In Go can use the following unary operators: & ! * + { ^<.
Unary^operator is operator of "complementary" (bitwise negation).
In Go, operators C: "++" and "- -", are not recognized as operators for expressions,
they are considered statements, but their eect is the same. Operators +=, -=, etc. have
the same functionality as in C.
12
Operator new
In Go the operator new() is used as in C++, is a call to a function. It returns a pointer
to the created object:
var t *Point = new(Point)
z := new(int) // z is of type *int
Don't use methods such as delete orfree to release memory as in C++, in Go have
aGarbage collector that frees unused memory and allocated memory.
Assignment operators
As in other programming languages operator =is used for assignment. In the Go
programming language is allowed multiple assignments, meaning, using a single call of
operator can be assigned multiple variables with dierent values:
u, t, v = f1(), f2(), f3()
m, n = 1, 10/5
where f1(), f2(), f3() are functions.
If the function returns more than one value (which is possible in Go), is used the
operator: :=.
nbytes, eroare := Write(buf)
1.3.4 Control structures
The instructions in GO are similar to those of C or Java, but are improved, so that
initialization can use in the if statement or two counters in a single statement for.
If
In Go a simple if statement looks like this:
1i fa>0f
2 return b
3g
here we don't use anymore ( )and thefgare required. Using GO initialization of
variables can be made since the declaration of instruction condition.
1i fx:=0 f ( ) ; x <20f
2 fmt . P r i n t f ( "%d x i s smaller than 20 nn" )
3g
4elsef
5 fmt . P r i n t f ( "%d x i s not smaller than 20 nn" )
6g
where f()is a function that returns an integer value. To use this feature should be that
after initialization to use the empty statement ";".
13
For
In Go a simple if statement looks like this:
1for i :=0; i <10; i++f. . .g
Where conditions are missing loop enters a innite cycle:
1for ; ;ffmt . P r i n t f ( " i n f i n i t e c y c l e " ) g
1forffmt . P r i n t f ( " i n f i n i t e c y c l e " ) g
Also, it can use multiple counters declared in the same block, so the sequence is:
1for i :=0; i <M; i++
2f
3 for j :=M; j >0; j f . . .g
4g
a simple form of this is:
1for i , j :=0 , M; i <M, j >0; i , j=i +1, j 1f. . .g
Switch
The statement switch in Go is more general than in C, it has fewer restrictions and
more features, such as:
the expressions need not be constants or integers;
is not necessary to use the instruction break;
if returning the same result can be written on the one case separated by commas;
if you want to through all the branches of instruction, will be added at the end of
instructions at each branch – fallthrough;
the cases are evaluated top to bottom until a match is found, and if the switch has
no expression it switches on true.
1switch count%9f
2 case 3 , 4 , 5 : e r r o r ( ) ;
3 case 2 : x=i ; f a l l t h r o u g h ;
4 case 1 : x=i ; f a l l t h r o u g h ;
5 case 0 :return xi ;
6g
14
1x , y:=a [ i ] , b [ j ] ;
2switchf
3 case x<y :return 1;
4 case x==y : return 0 ;
5 case x>b :return 1 ;
6g
or:
1switch x , y := a [ i ] , b [ j ] ; f. . .g
At the same like in C, and in Go the statement swich has branch default :
1switch xf
2 case 0 : fmt . P r i n t f ( "0" )
3 default : fmt . p r i n t f ( " nonzero " )
4g
1.3.5 Errors
The Go libraries can return some sort of error indication to the caller, error values are
used to indicate an abnormal state. Errors have type error, a simple built-in interface:
1type e r r o r interfacef
2 Error ( ) s t r i n g
3g
Close function returns a non-nil error value when it fails to close a le:
1func Close (name s t r i n g ) ( f i l e File , e r r e r r o r )
The fmtpackage formats an error value and know to call the method when asked to
print an error. If the error is unrecoverable and the program can't continue it is use a
built-in function panic , that in eect creates a run-time error that will stop the program.
When panic is called it immediately stops execution, and the program can die, but
it is possible to use the built-in function recover to regain control of the goroutine and
resume normal execution. Recover is only useful inside deferred functions and is used to
shut down a failing goroutine without killing the other executing goroutines.
15
Chapter 2
Concurrent programming in Go
Concurrent programming is the development of programs that consist of segments that
have the property for parallel execution. Concurrent programming is useful in modeling
or simulating physical systems, even if those systems are not directly controlled by a
computer. For example, the waiting and service times in a bank, supermarket, or other
service organization can be studied by writing a program in which each customer and
each server { bank teller, supermarket checker, airline reservation clerk{is represented by
its own program segment, which interacts with the other segments. [10]
In concurrent programming a process is an execution of a program segment. Advan-
tages of concurrent programming is that multiple programs can be executed simultane-
ously and the programs have potentially by interacting with each other.
The primitives for concurrency present in Go provide an elegant and distinct means
of structuring concurrent software. These concepts are goroutines and channels. Go
channels synchronize and communicate; the sending goroutine waits until the receiving
goroutine is ready to accept the communication.
2.1 Goroutines
In the Go documentation we nd "Goroutines are multiplexed onto multiple OS
threads so if one should block, such as while waiting for I/O, others continue to run". A
goroutine allow executing tasks concurrently at the same address. Goroutines in Go are
similar to normal functions, but you have to attach a goin front of the actual function
call. A program can have more than one goroutine.
" There are a few things to keep in mind about Go's goroutines.
They are not threads in the sense of java's or c++ threads.
– they are more like greenlets.
The go runtime multiplexes the goroutines across the system threads
– the number of system threads is controlled by an environment variable GOMAX-
PROCS and defaults to 1 currently I think. This may change in the future.
16
The way goroutines yield back to their current thread is controlled by several dif-
ferent constructs.
– the select statement can yield control back to the thread.
– sending on a channel can yield control back to the thread.
– doing IO operations can yield control back to the thread.
– runtime.Gosched() explicitly yields control back to the thread.
The behavior you are seeing is caused by because the main function never yields back to
the thread and is instead involved in a busy loop and since there is only one thread the
main loop has no place to run." [11]
A routine ends when its reaches its end or the method runtime.Goexit method() is
called.
2.2 Channels
The most convenient method used for synchronization in Go are channels. Channels
are used to send and receive messages between routines and for synchronization of routines.
When using the communication channels, the comunication is synchronous. If we do not
have the same type of receiver as transmitter, to receive information transmitted, the
communication channel is locked, and vice versa.
Declaring a data type that will use a communication channel is made by:
chan data type
Because channels are reference types, variables used in the communication channels
are initialized with the function make:
var ch := make(chan bool)
to the variable ch is assigned a communication channel for the type bool.
To transmit data over this channel is used the operator <{. When sending a value
place the channel on the left side of the <{ operator, and when we get a value place the
channel on the right. The order how we send and receive messages is very important. If
the channel has no direction , the channel is bi-directional.
sending message on the channel ch is:
ch<– true //true value is transmitted on ch
To assign a value transmitted by channel ch to a variable we use the operator =, and
to initiate a variable with a value transmitted by the channel ch we use the operator :=.
If we don't use the sent value is not necessary to write this, declare as:
<– ch
17
Example 2.2.1
1package main
3import "fmt"
5func g e n e r a t e i n t e g e r s ( ) chan intf
6 ch := make( chan int) ;
7 go func ()f
8 for i := 2 ; ; i++ f
9 ch<
