通信顺序过程 (Communicating sequential processes, CSP) 是一种用于描述并发系统中交互模式的形式语言。讲究的是”通过 通信 来共享内存, 而非通过共享内存来通信”

    1. package testa
    2. import (
    3. "fmt"
    4. "testing"
    5. "time"
    6. )
    7. func service() string {
    8. time.Sleep(time.Millisecond * 50)
    9. return "done"
    10. }
    11. func otherTask() {
    12. fmt.Println("working on something else")
    13. time.Sleep(time.Millisecond * 100)
    14. fmt.Println("task is done")
    15. }
    16. func Test1(t *testing.T) {
    17. start := time.Now()
    18. ret := service()
    19. fmt.Println(ret)
    20. otherTask()
    21. t.Log("Test1 cost:", time.Since(start)) // Test1 cost: 157.401782ms
    22. }
    23. func AsyncService() chan string {
    24. retCh := make(chan string)
    25. go func() {
    26. ret := service()
    27. retCh <- ret
    28. }()
    29. return retCh
    30. }
    31. func Test2(t *testing.T) {
    32. start := time.Now()
    33. retCh := AsyncService()
    34. otherTask()
    35. fmt.Println(<-retCh)
    36. t.Log("Test2 cost:", time.Since(start)) // Test2 cost: 104.309487ms
    37. }