概述

语言传统同步方式

  • atomic
  • waitGroup
  • mutex
  • cond
  • http client

同步

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. type atomicInt struct {
  8. value int
  9. lock sync.Mutex
  10. }
  11. func (a *atomicInt) increment() {
  12. fmt.Println("safe increment")
  13. func() {
  14. a.lock.Lock()
  15. defer a.lock.Unlock()
  16. a.value++
  17. }()
  18. }
  19. func (a *atomicInt) get() int {
  20. a.lock.Lock()
  21. defer a.lock.Unlock()
  22. return a.value
  23. }
  24. func main() {
  25. var a atomicInt
  26. a.increment()
  27. go func() {
  28. a.increment()
  29. }()
  30. time.Sleep(time.Millisecond)
  31. fmt.Println(a.get())
  32. }

http client
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httputil"
  6. )
  7. func main() {
  8. request, err := http.NewRequest(
  9. http.MethodGet,
  10. "http://www.ctoedu.com", nil)
  11. request.Header.Add("User-Agent",
  12. "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1")
  13. client := http.Client{
  14. CheckRedirect: func(
  15. req *http.Request,
  16. via []*http.Request) error {
  17. fmt.Println("Redirect:", req)
  18. return nil
  19. },
  20. }
  21. resp, err := client.Do(request)
  22. if err != nil {
  23. panic(err)
  24. }
  25. defer resp.Body.Close()
  26. s, err := httputil.DumpResponse(resp, true)
  27. if err != nil {
  28. panic(err)
  29. }
  30. fmt.Printf("%s\n", s)
  31. }

image.jpeg