1. 只运行一次

image.png
image.png

  1. package once_test
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. "unsafe"
  7. )
  8. type Singleton struct {
  9. }
  10. var singleInstance *Singleton
  11. var once sync.Once
  12. func GetSingletonObj() *Singleton {
  13. once.Do(func() {
  14. fmt.Println("Create obj")
  15. singleInstance = new(Singleton)
  16. })
  17. return singleInstance
  18. }
  19. func TestGetSingletonObj(t *testing.T) {
  20. var wg sync.WaitGroup
  21. for i := 0; i < 10; i++ {
  22. wg.Add(1)
  23. go func() {
  24. obj := GetSingletonObj()
  25. fmt.Printf("%x\n", unsafe.Pointer(obj))
  26. wg.Done()
  27. }()
  28. }
  29. wg.Wait()
  30. }

2. 仅需任意任务完成

  1. package concurrency
  2. import (
  3. "fmt"
  4. "runtime"
  5. "testing"
  6. "time"
  7. )
  8. func runTask(id int) string {
  9. time.Sleep(10 * time.Millisecond)
  10. return fmt.Sprintf("The result is from %d", id)
  11. }
  12. func FirstResponse() string {
  13. numOfRunner := 10
  14. //采用buffer channel 来防止协程泄露
  15. ch := make(chan string, numOfRunner)
  16. //ch := make(chan string)
  17. for i := 0; i < numOfRunner; i++ {
  18. go func(i int) {
  19. ret := runTask(i)
  20. ch <- ret
  21. }(i)
  22. }
  23. return <-ch
  24. }
  25. func TestFirstResponse(t *testing.T) {
  26. t.Log("Before:", runtime.NumGoroutine())
  27. t.Log(FirstResponse())
  28. time.Sleep(time.Second * 1)
  29. t.Log("After:", runtime.NumGoroutine())
  30. }

3. 所有任务完成

  1. package util_all_done
  2. import (
  3. "fmt"
  4. "runtime"
  5. "testing"
  6. "time"
  7. )
  8. func runTask(id int) string {
  9. time.Sleep(10 * time.Millisecond)
  10. return fmt.Sprintf("The result is from %d", id)
  11. }
  12. func FirstResponse() string {
  13. numOfRunner := 10
  14. ch := make(chan string, numOfRunner)
  15. for i := 0; i < numOfRunner; i++ {
  16. go func(i int) {
  17. ret := runTask(i)
  18. ch <- ret
  19. }(i)
  20. }
  21. return <-ch
  22. }
  23. func AllResponse() string {
  24. numOfRunner := 10
  25. ch := make(chan string, numOfRunner)
  26. for i := 0; i < numOfRunner; i++ {
  27. go func(i int) {
  28. ret := runTask(i)
  29. ch <- ret
  30. }(i)
  31. }
  32. finalRet := ""
  33. for j := 0; j < numOfRunner; j++ {
  34. finalRet += <-ch + "\n"
  35. }
  36. return finalRet
  37. }
  38. func TestFirstResponse(t *testing.T) {
  39. t.Log("Before:", runtime.NumGoroutine())
  40. t.Log(AllResponse())
  41. time.Sleep(time.Second * 1)
  42. t.Log("After:", runtime.NumGoroutine())
  43. }

4. 对象池

image.png

5. sync.pool对象缓存

image.png
image.png
image.png
image.png
image.png