Task switching traditionaly used to achieve concurrency.
C++ paradigm:
Go paradigm:
Design && Limiting factor
Finer grained concurrency. Pipeline parallelism.
DAG
Speedup: best sequential execution time over the parallel execution time.
\[S_p(n) = \frac{T_\text{best seq}(n)}{T_p(n)}\]Speedup of parallel execution is limited by the fraction of the algorithm that cannot be parallelized ($f$).
Amdahl’s law: speed up limited by the sequential fraction $f$ (time of program that must execute sequentially).
Developed by Hoare 1978.
Refined to process calculus.
go function
runs on OS thread.channel<-
and <-channel
select
statementRuntime multiplexes goroutines onto OS threads. Multiple goroutines in a thread “bucket”. Decouples concurrency from parallelism.
Scheduling algorithm
When a goroutine blocks, the thread blocks.
Goroutines are not garbage collected.
Goroutines need to have join point specified
defer
to execute on exit scopemake(chan myType)
func(myCh <-chan myType)
myVal := <-myCh
func(myCh chan<- myType)
myCh <- val
To loop over an entire channel via range;
for integer := range intStream {
fmt.Printf("%v ", integer)
}
Buffered channel: make(chan myType, bufCount)
Send will block once buffer is full, until a value is read from the buffer.
Owner: Write-access view of a channel
Consumer: Read-access view of a channel
select
statementsGo’s blocking equivalent of switch. it
default
case.Pseudo-random:
c1 := make(chan int); close(c1)
c2 := make(chan int); close(c2)
v1 := 0
v2 := 0
for i = 0; i < 1000; i++ {
select { // v1 approx same as v2
case <-c1:
v1++
case <-c2:
v2++
}
}
Timeout:
select {
case <-chanToWaitFor:
doSmth()
case <-time.After(1 * time.Second): // select may still choose this when there are non-blocking channels
fmt.Println("Timeout")
// default: // do some work
}
go
stmt that starts new goroutine is sync-before the goroutine’s executionsend
is sync-before rcv
on the same channelclose
is sync-before a rcv
returning zero-valuercv
on unbuffered channel is sync-before send on that channelk
th rcv on buffered channel C of size $C$ is sync-before k+C
th send