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()
}
本文探讨了Go语言中基于CSP(Communicating Sequential Processes)的并发模型,通过Channel实现进程间的松耦合通讯,与Actor模型进行对比。在Go中,Channel具有容量限制并独立于goroutine,而Erlang的Actor模式则使用无限制的mailbox。示例代码展示了如何在Go中使用Channel进行异步服务调用。
327

被折叠的 条评论
为什么被折叠?



