![]() |
|
Golang Tutorial #4 - Channels and GoRoutines - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: Coding (https://sinister.ly/Forum-Coding--71) +--- Thread: Golang Tutorial #4 - Channels and GoRoutines (/Thread-Golang-Tutorial-4-Channels-and-GoRoutines) |
Golang Tutorial #4 - Channels and GoRoutines - Inori - 05-13-2016 Everything in the series thus far has been basic(ish) and only deals with a single thread. This tutorial explains GoRoutines and Channels, which are the Threads and Thread Variables of Go. GoRoutines Goroutines, compared to Python threading, are extremely simple. Just by using the "go" keyword, the program starts a concurrent thread with the function that follows it. See the below examples (only relevant code). Code: func printAdd(a,b int){
fmt.Println(a+b)
}
func main(){
// starts the thread with the printAdd function
go printAdd(1,2)
// also works with anonymous functions (equivalent function)
go func(a,b int){
fmt.Println(a+b)
}(1,2)
}Channels Channels are more or less global pipes. One way the function is acting as a return for functions without a return in their signature. Code: // make the channel
var ch=make(chan int)
// add function
func add(a,b int){
// get result
res:=a+b
// write to channel
ch<-res
}
// main function
func main(){
// call the add function
add(1,2)
// get the value from the channel, and set value equal to it
value:=<-ch
// print value
fmt.Println(value)
}Combining the two A combination of Channels and GoRoutines could be shown as follows: Code: // make channel
var ch=make(chan int)
// add function
func add(a,b int){
// get result
res:=a+b
// send result to channel
ch<-res
}
// function to receive from channel
func recv(){
// get result from channel (synchronous operation, waits for data)
res:=<-ch
fmt.Println(res)
}
// main function
func main(){
// create goroutine for add function
go add(1,2)
// call synchronous recv() function
recv()
}Syntax GoRoutines: Code: // defined function
go myFunction(params)
// anonymous function
go func(params types){
// do function stuff
}(params)Channels Code: // create channel
ch:=make(chan type)
// send to channel
ch<-data
// get data from channel
variable:=<-chSorry I couldn't go too in-depth for this one, I'm very busy with school, but just built a TCP server using these techniques, so I thought it'd be good to share. |