Golang

 

Concurrency is NOT paralelism

 

So... what is it then?

Let's explore concurrency a bit more!

 

Let's be parallel!

 

Now, lets try only concurrency

Of course we can do this in parallel 

Ok. Let's get technical.

 

http://www.golang-book.com/

http://tour.golang.org/#1

What is go's concurrency mechanism?

  • lightweight - you can have ten's of thousands
  • non-blocking (well... not exactly)
  • Is sometimes paralell (depends on the design)

Go routines

 

Example:

http://play.golang.org/p/NDmq3Nkszw

package main

import (
	"fmt"
	"time"
)

type Manager struct {
	In      chan func()
	done    chan error
	timeout chan struct{}
}

func NewManager(workers int, timeout time.Duration) *Manager {
	m := &Manager{
		In:      make(chan func(), 16*workers),
		done:    make(chan error, workers),
		timeout: make(chan struct{}),
	}
	time.AfterFunc(timeout, func() {
		close(m.timeout)
	})
	for w := 0; w < workers; w++ {
		go func() {
			for {
				select {
				case f, ok := <-m.In:
					if !ok {
						m.done <- nil
						return
					}
					f()
				case <-m.timeout:
					m.done <- fmt.Errorf("timed out")
				}
			}
		}()

What about complex communication?

Chanells

http://play.golang.org/p/fruJiGBWjn

package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(linkChan chan string, wg *sync.WaitGroup) {
	// Decreasing internal counter for wait-group as soon as goroutine finishes
	defer wg.Done()

	for url := range linkChan {
		time.Sleep(1 * time.Second)
		fmt.Printf("Done processing link #%s\n", url)
	}

}

func main() {
	yourLinksSlice := make([]string, 50)
	for i := 0; i < 50; i++ {
		yourLinksSlice[i] = fmt.Sprintf("%d", i+1)
	}

	lCh := make(chan string)
	wg := new(sync.WaitGroup)

	// Adding routines to workgroup and running then
	for i := 0; i < 3; i++ {
		wg.Add(1)
		go worker(lCh, wg)
	}

	// Processing all links by spreading them to `free` goroutines
	for _, link := range yourLinksSlice {
		lCh <- link
	}

	// Closing channel (waiting in goroutines won't continue any more)
	close(lCh)

	// Waiting for all goroutines to finish (otherwise they die as main routine dies)
	wg.Wait()

Sum up:

  • Concurrency is a way to design your programs.
  • It leads to some very nice things.
  • Concurrency in go is very cheap and easy to implement.
  • There are no deadlocks.

Questions?

  • How are go routines implemented?
  • How are they different from threads? / Why not use threads?
  • Do I need to keep go-routines alive like threads to preserve variables that are slow to create like db / file handlers ?
  • How much wood could a woodchuck chuck

    If a woodchuck could chuck wood?

Golang

By Zlatin Stanimirov

Golang

  • 1,460