CSP vs Actor
- 和Actor的直接通讯不同,CSP模式则是通过Channel进行通讯,更松耦合些
- Go中的channel是有容量限制并且独立于处理Groutine,而如Erlang,Actor模式中的mailbox容量是无限的,接收进程也总是被动的处理消息
package csp
import (
"fmt"
"testing"
"time"
)
func Service() string{
time.Sleep(time.Millisecond * 50)
return "Done"
}
func otherTask() string{
fmt.Println("working on something else")
time.Sleep(time.Millisecond * 100)
fmt.Println("Task is Done")
return "Done"
}
func AsyncService() chan string{
retCh := make(chan string,1)
go func() {
ret := Service()
fmt.Println("returned result")
retCh <- ret //buffer channel异步 channel同步
fmt.Println("service exited")
}()
return retCh
}
func TestAsynService(t *testing.T){
retch := AsyncService()
otherTask()
fmt.Println(<-retch)
}
func TestService(t *testing.T){
fmt.Println(Service())
otherTask()
}