为什么这个RPC服务器不能扩展?

huangapple go评论129阅读模式
英文:

Why does not this RPC server scale?

问题

这段代码启动了一个RPC服务器和100个并行的客户端,但是尽管GOMAXPROCS已经正确配置,它从未使用超过1个CPU。

那么是什么阻止它使用更多的CPU呢?如何改善这种情况?

这个问题的原因是在代码中没有显式地设置并发执行的最大CPU数。默认情况下,Go语言的运行时系统会根据可用的逻辑CPU数来设置GOMAXPROCS的值,以实现并行执行。但是在这段代码中,GOMAXPROCS没有被设置,因此默认值为1,即只使用一个CPU。

要改善这种情况,可以在代码中显式地设置GOMAXPROCS的值,以允许并行执行。可以通过调用runtime.GOMAXPROCS函数来设置GOMAXPROCS的值,例如:

  1. import "runtime"
  2. func main() {
  3. // 设置GOMAXPROCS的值为2,表示允许最多使用2个CPU并行执行
  4. runtime.GOMAXPROCS(2)
  5. // 其他代码...
  6. }

通过设置GOMAXPROCS的值为大于1的数,可以允许代码并行执行,从而更好地利用多个CPU。请根据实际情况设置合适的值,以获得最佳的性能提升。

英文:
  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "net/rpc"
  6. "sync"
  7. )
  8. type SumInput struct {
  9. UpTo int
  10. }
  11. type SumOutput struct {
  12. Result int
  13. }
  14. type RpcServer struct {
  15. }
  16. func (s *RpcServer) Calculate(in *SumInput, out *SumOutput) error {
  17. for i := 0; i < in.UpTo; i++ {
  18. out.Result += i
  19. }
  20. return nil
  21. }
  22. func main() {
  23. server := new(RpcServer)
  24. rpc.Register(server)
  25. sock, err := net.Listen("tcp", ":1234")
  26. if err != nil {
  27. panic(err)
  28. }
  29. go func() {
  30. for {
  31. conn, err := sock.Accept()
  32. if err != nil {
  33. panic(err)
  34. }
  35. go rpc.ServeConn(conn)
  36. }
  37. }()
  38. wg := &sync.WaitGroup{}
  39. wg.Add(100)
  40. for i := 0; i < 100; i++ {
  41. go func(i int) {
  42. client, err := rpc.Dial("tcp", "127.0.0.1:1234")
  43. if err != nil {
  44. panic(err)
  45. }
  46. rpcOut := &SumOutput{}
  47. err = client.Call("RpcServer.Calculate", &SumInput{100000000}, rpcOut)
  48. if err != nil {
  49. panic(err)
  50. }
  51. fmt.Println("Got reply: ", rpcOut, i)
  52. wg.Done()
  53. }(i)
  54. }
  55. wg.Wait()
  56. }

It starts an RPC server and 100 clients in parallel, but it never makes use of more than 1 CPUs, despite that GOMAXPROCS is properly configured.

So what was stopping it from using more CPUs? And how to improve the situation?

答案1

得分: 2

我尝试了你的示例,并且在我的笔记本电脑上成功地使用了所有8个CPU。

  1. GOMAXPROCS=8 go run rpctest.go

所以我猜你在设置GOMAXPROCS环境变量时出了问题。你是不是在单独的一行设置了它,然后忘记导出它了?

  1. export GOMAXPROCS=8

通常我会在程序中使用runtime模块来设置它

  1. runtime.GOMAXPROCS(runtime.NumCPU())
英文:

I tried your example like this and it worked fine using all 8 CPUs on my laptop

  1. GOMAXPROCS=8 go run rpctest.go

So at a guess you messed up setting the GOMAXPROCS environment variable somehow. Did you set it on a separate line and forget to export it?

  1. export GOMAXPROCS=8

Normally I set this in program using the runtime module

  1. runtime.GOMAXPROCS(runtime.NumCPU())

huangapple
  • 本文由 发表于 2014年1月26日 18:05:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/21362099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定