/Concurrency in “Go” Programming Language

Concurrency in “Go” Programming Language

The following two tabs change content below.

Tom Maciejewski

Latest posts by Tom Maciejewski (see all)

Last week we discussed why you should consider leaving languages like Java and Python and switching to Go. I provided a quick example of how to write a web server using go, pretty easy right? This week I wanted to dive into something a bit more in depth to show off the power of Go: concurrency.

No real programming interview (in any programming language) is complete without a question about threads and or concurrency.   Whether you plan on using Go or not, and I highly recommend that you do, learning a few things on this topic will help you out in an interview, and maybe even in one of your classes.

Tip #1

Concurrency, although usually associated with multithreading, is NOT the same as multithreading. In fact, you can do concurrent programming in a single thread. Here is an example using Go.

In Go there is something called a channel.   Channels allow two goroutines to communicate.

Make a channel:

myChannel := make(chan int)

Push to a channel:

myChannel <- 42

Read from a channel:

value = <- myChannel  Channels can be used with select statements in Go. Here is an example: select {      case v1 := <- myChannel:            fmt.Printf(“%v from myChannel\n”, v1)      case v2 := <-c2:            fmt.Printf(“received %v from yourChannel \n”, v1)      case c3 <- 23:            fmt.Printf(“Sending data using select”, 23)      default:            fmt.Printf(“None of the channels were ready\n”)     } Here is a cool working example from http://play.golang.org/p/9U22NfrXeq // A concurrent prime sieve package main // Send the sequence 2, 3, 4, … to channel ‘ch’.func Generate(ch chan<- int) {       for i := 2; ; i++ {             ch <- i // Send ‘i’ to channel ‘ch’.       }} // Copy the values from channel ‘in’ to channel ‘out’,// removing those divisible by ‘prime’.func Filter(in <-chan int, out chan<- int, prime int) {       for {             i := <-in // Receive value from ‘in’.             if i%prime != 0 {                    out <- i // Send ‘i’ to ‘out’.             }       }}// The prime sieve: Daisy-chain Filter processes.func main() {       ch := make(chan int) // Create a new channel.       go Generate(ch)     // Launch Generate goroutine.       for i := 0; i < 10; i++ {             prime := <-ch             print(prime, “\n”)             ch1 := make(chan int)             go Filter(ch, ch1, prime)             ch = ch1       }}

Take a look and nuances here to really grasp some of the beauty of the Go programming language. See if you can figure out how this program works. I will discuss this further in upcoming articles. If you have any questions about Go, this program or this article drop me an email at etm8@njit.edu.

 

 

 

 

 

 

TAGS: