Skip to content

Commit

Permalink
concurrency
Browse files Browse the repository at this point in the history
  • Loading branch information
GoesToEleven committed Nov 25, 2015
1 parent dcf26b7 commit e443987
Showing 1 changed file with 37 additions and 24 deletions.
61 changes: 37 additions & 24 deletions 100_GDGSV/in-progress/03_race-condition/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,28 +7,24 @@ import (
"log"
"os"
"path/filepath"
"time"
"sync"
"io/ioutil"
"time"
)

// at terminal:
// go run -race main.go

var counter int
var wg sync.WaitGroup

type pixel struct {
r, g, b, a uint32
}

func main() {
start := time.Now()
dir := "../photos/"
files,_ := ioutil.ReadDir(dir)
wg.Add(len(files))
fmt.Println("FILES TO PROCESS:",len(files))
images := getImages(dir)

images, err := getImages()
if err != nil {
log.Println("Error getting images", err)
}

// range over the [] holding the []pixel - eg, give me each img
// range over the []pixel hold the pixels - eg, give me each pixel
Expand All @@ -40,30 +36,49 @@ func main() {
}
}
}
wg.Wait()
fmt.Println("Holy cow:", counter)

fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}

func getImages(dir string) [][]pixel {

var images [][]pixel
func getImages() ([][]pixel, error) {
const dir = "../../photos/"

filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
var paths []string
f := func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
paths = append(paths, path)
return nil
}

go (func(){
if err := filepath.Walk(dir, f); err != nil {
return nil, err
}

var mu sync.Mutex
var wg sync.WaitGroup
wg.Add(len(paths))

var images [][]pixel
for _, path := range paths {
go func(path string) {
img := loadImage(path)
pixels := getPixels(img)
images = append(images, pixels)

mu.Lock()
{
images = append(images, pixels)
}
mu.Unlock()

wg.Done()
})()
return nil
})
}(path)
}

return images
wg.Wait()

return images, nil
}

func loadImage(filename string) image.Image {
Expand All @@ -82,7 +97,6 @@ func loadImage(filename string) image.Image {
}

func getPixels(img image.Image) []pixel {

bounds := img.Bounds()
fmt.Println(bounds.Dx(), " x ", bounds.Dy()) // debugging
pixels := make([]pixel, bounds.Dx()*bounds.Dy())
Expand All @@ -95,7 +109,6 @@ func getPixels(img image.Image) []pixel {
pixels[i].g = g
pixels[i].b = b
pixels[i].a = a
counter++
}

return pixels
Expand Down

0 comments on commit e443987

Please sign in to comment.