Skip to content

Instantly share code, notes, and snippets.

@kayslay
Created December 18, 2019 23:32
Show Gist options
  • Save kayslay/efd453d766d91016b53e0cf52f851fa1 to your computer and use it in GitHub Desktop.
Save kayslay/efd453d766d91016b53e0cf52f851fa1 to your computer and use it in GitHub Desktop.
package main
import (
"io"
"sync"
"time"
)
// a function that does much cpu bound work
func fibo(n int) int {
if n < 2 {
return 1
}
return fibo(n-2) + fibo(n-1)
}
// run sequentially
func cpuExampleSequential() {
for i := 0; i < 10; i++ {
fibo(40)
}
}
// run concurrently
func cpuExampleConcurrent() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fibo(40)
}()
}
wg.Wait()
}
type sleepReader struct {
delay time.Duration
}
func (sr sleepReader) Read(b []byte) (int, error) {
time.Sleep(sr.delay)
copy(b, []byte("hello world"))
return 0, nil
}
func read(r io.Reader) {
b := make([]byte, 10)
r.Read(b)
}
func ioExampleSequential() {
for i := 0; i < 10; i++ {
read(sleepReader{time.Second * 3})
}
}
func ioExampleConcurrent() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
read(sleepReader{time.Second * 3})
}()
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment