Skip to content

Instantly share code, notes, and snippets.

@shelomentsevd
Created October 23, 2017 09:49
Show Gist options
  • Select an option

  • Save shelomentsevd/8d84bf38dfb44aa029d4b272cbb3c693 to your computer and use it in GitHub Desktop.

Select an option

Save shelomentsevd/8d84bf38dfb44aa029d4b272cbb3c693 to your computer and use it in GitHub Desktop.
package main
import (
"sync/atomic"
"fmt"
)
type Increment struct {
count uint32
}
func main() {
increment := Increment{}
start := make(chan struct{})
activity := func(i *Increment) {
<-start
atomic.AddUint32(&i.count, 1)
}
for i := 0; i < 100; i++ {
go activity(&increment)
}
close(start)
fmt.Printf("INCR: %d", increment.count)
}
@shelomentsevd
Copy link
Copy Markdown
Author

package main

import (
	"sync/atomic"
	"fmt"
	"sync"
)

type Increment struct {
	count uint32
}

func main() {
	wg := sync.WaitGroup{}
	wg.Add(10000)
	increment := Increment{}
	start := make(chan struct{})
	activity := func(i *Increment, wg * sync.WaitGroup) {
		<-start
		atomic.AddUint32(&i.count, 1)
		wg.Done()
	}

	for i := 0; i < 10000; i++ {
		go activity(&increment, &wg)
	}

	close(start)

	wg.Wait()
	fmt.Printf("INCR: %d", increment.count)
}

Забыл добавить WaitGroup

@Amirkin
Copy link
Copy Markdown

Amirkin commented Oct 23, 2017

package main

import (
	"sync/atomic"
	"fmt"
	"sync"
)

type Increment struct {
	count uint32
}

func main() {
	wg := sync.WaitGroup{}

	increment := Increment{}
	start := make(chan struct{})
	activity := func(i *Increment) {
		<-start
		atomic.AddUint32(&i.count, 1)
		wg.Done()
	}

	for i := 0; i < 10000; i++ {
                wg.Add(1)
		go activity(&increment)
	}

	close(start)

	wg.Wait()
	fmt.Printf("INCR: %d", increment.count)
}

Так не лучше?

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