通信顺序过程 (Communicating sequential processes, CSP) 是一种用于描述并发系统中交互模式的形式语言。讲究的是”通过 通信 来共享内存, 而非通过共享内存来通信”
package testaimport ("fmt""testing""time")func service() string {time.Sleep(time.Millisecond * 50)return "done"}func otherTask() {fmt.Println("working on something else")time.Sleep(time.Millisecond * 100)fmt.Println("task is done")}func Test1(t *testing.T) {start := time.Now()ret := service()fmt.Println(ret)otherTask()t.Log("Test1 cost:", time.Since(start)) // Test1 cost: 157.401782ms}func AsyncService() chan string {retCh := make(chan string)go func() {ret := service()retCh <- ret}()return retCh}func Test2(t *testing.T) {start := time.Now()retCh := AsyncService()otherTask()fmt.Println(<-retCh)t.Log("Test2 cost:", time.Since(start)) // Test2 cost: 104.309487ms}
