Skip to content

Instantly share code, notes, and snippets.

@ernestoalejo
Last active February 28, 2020 23:11
Show Gist options
  • Save ernestoalejo/ba34c3ca377ef78c96840728f62f01cc to your computer and use it in GitHub Desktop.
Save ernestoalejo/ba34c3ca377ef78c96840728f62f01cc to your computer and use it in GitHub Desktop.
func foo() {
mylist := []*thing{...}
var wg sync.WaitGroup
ch := make(chan *thing)
for i := 0; i < maxWorkers; i++ {
wg.Add(1)
go worker(&wg, ch)
}
for _, item := range mylist {
ch <- item
}
close(ch)
wg.Wait()
}
func worker(wg *sync.WaitGroup, ch chan *thing) {
defer wg.Done()
for item := range ch {
... process item
}
}
func foo() {
mylist := []*thing{...}
var wg sync.WaitGroup
ch := make(chan *thing)
results := make(chan int, maxWorkers)
for i := 0; i < maxWorkers; i++ {
wg.Add(1)
go worker(&wg, ch, results)
}
for _, item := range mylist {
ch <- item
}
close(ch)
wg.Wait()
var succeeded int64
for imported := range results {
succeeded += imported
}
log.Println("Users successfully imported", succeeeded)
}
func worker(wg *sync.WaitGroup, ch chan *thing, results chan int64) {
defer wg.Done()
var imported int64
for item := range ch {
if err := blahblah(); err != nil {
...
continue
}
... process item
imported++
}
results <- imported
}
@gomezjdaniel
Copy link

func foo() {
	mylist := []*thing{...}
	
	var wg sync.WaitGroup
	ch := make(chan *thing)
	for i := 0; i < maxWorkers; i++ {
		wg.Add(1)
		go worker(&wg, ch)
	}
	for i, item := range mylist {
               if i != 0 && i%100 == 0 {
                 log.Printf("%d customers proccesed so far", i)
               }
		ch <- item
	}
	close(ch)
	wg.Wait()
}

func worker(wg *sync.WaitGroup, ch chan *thing) {
	defer wg.Done()
	for item := range ch {
		... process item
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment