Communcating sequential processes (CSP)git
先看一段代码github
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 TestService(t *testing.T) {
fmt.Println(service())
otherTask()
}
复制代码
输出shell
=== RUN TestService
Done
working on something else
task is done.
--- PASS: TestService (0.15s)
PASS
Process finished with exit code 0
复制代码
能够看出上述打印结果是按照程序执行的顺序 下边是用 Channelui
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 AsyncService() chan string {
retCh := make(chan string)
go func() {
ret := service()
fmt.Println("returned result.")
retCh <- ret
fmt.Println("service exited.")
}()
return retCh
}
func TestAsyncService(t *testing.T) {
retCh := AsyncService()
otherTask()
fmt.Println(<-retCh)
time.Sleep(time.Second * 1)
}
复制代码
输出spa
=== RUN TestAsyncService
working on something else
returned result.
task is done.
Done
service exited.
--- PASS: TestAsyncService (1.11s)
PASS
Process finished with exit code 0
复制代码
使用了channel ,能够看到 service exited. 消息打印在了最后,因此,即使咱们channel里边放进了消息,其余的task没有结束以前,service的那个协程都会被阻塞住,直到channel 消息被接收掉; 下边使用buffer channelcode
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 AsyncService() chan string {
//retCh := make(chan string)
retCh := make(chan string,1)
go func() {
ret := service()
fmt.Println("returned result.")
retCh <- ret
fmt.Println("service exited.")
}()
return retCh
}
func TestAsyncService(t *testing.T) {
retCh := AsyncService()
otherTask()
fmt.Println(<-retCh)
time.Sleep(time.Second * 1)
}
复制代码
输出协程
=== RUN TestAsyncService
working on something else
returned result.
service exited.
task is done.
Done
--- PASS: TestAsyncService (1.11s)
PASS
Process finished with exit code 0
复制代码
这个时候咱们能看到 Done 这个消息打印到了 service exited. 后边,说明那个service 协程没有被阻塞,执行完就释放掉了, channel 里的消息在 otherTask 执行完之后, 正确的打印了出来;进程
笔记出处 github.com/wenjianzhan…get