147
edits
Changes
→Halt and Catch Fire
*Go allows multi-core programming using concurrency methods, and enables the ability to parallelize.
== TLDR; ==
[[Image:Concurrency vs Parallelism.png|600px|thumb|alt=concurrency vs parallelism]]
=== What is parallelism? ===
*Programming as the simultaneous execution of (possibly related) computations.
=== Examples of things that use a parallel model ===
*GPU - performing vector dot products.
== Up and running with Go ==
=== Download and installation ===
*[https://golang.org/doc/install Download instructions]<br/>
*[https://golang.org/doc/install Installation Instructions]
=== Documentation ===
*[https://golang.org/doc/ About the language]
=== Playground ===
*[https://tour.golang.org/ Online tutorial]
== Demo: Concurrency and parallelism in Go ==
=== Monte Carlo Simulations ===
[[Image:Pi 30K.gif|500px|thumb|alt=Monte Carlo Simulations]]
*A probabilistic way to come up with the answer to a mathematical question by running a large number of simulations when you cannot get or want to double-check a closed-formed solution.<br/>
*Use it to calculate the value of π (pi) - 3.1415926535
==== Method ====
#Draw a square, then inscribe a circle within it.
#Uniformly scatter some objects of uniform size (grains of rice or sand) over the square.
#Count the number of objects inside the circle and the total number of objects.
#The ratio of the two counts is an estimate of the ratio of the two areas, which is π/4. Multiply the result by 4 to estimate π.
==== Pseudo implementation ====
*To make the simulations simple, we’ll use a unit square with sides of length 1.
*That will make our final ratio of: (π*(1)2/4) / 12 = π/4
*We just need to multiply by 4 to get π.
==== Implementation ====
===== Serial =====
<syntaxhighlight lang="go">
func PI(samples int) float64 {
var inside int = 0
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < samples; i++ {
x := r.Float64()
y := r.Float64()
if (x*x + y*y) <= 1 {
inside++
}
}
ratio := float64(inside) / float64(samples)
return ratio * 4
}
</syntaxhighlight>
===== Parallel =====
<syntaxhighlight lang="go">
func MultiPI(samples int) float64 {
runtime.GOMAXPROCS(runtime.NumCPU())
cpus := runtime.NumCPU()
threadSamples := samples / cpus
results := make(chan float64, cpus)
for j := 0; j < cpus; j++ {
go func() { // spawn goroutine
var inside int
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < threadSamples; i++ {
x, y := r.Float64(), r.Float64()
if (x*x + y*y) <= 1 {
inside++
}
}
results <- float64(inside) / float64(threadSamples) * 4
}()
}
var total float64
for i := 0; i < cpus; i++ {
total += <-results
}
return total / float64(cpus)
}
</syntaxhighlight>