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

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

Why does not this RPC server scale?

问题

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

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

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

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

import "runtime"

func main() {
    // 设置GOMAXPROCS的值为2,表示允许最多使用2个CPU并行执行
    runtime.GOMAXPROCS(2)

    // 其他代码...
}

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

英文:
package main

import (
	"fmt"
	"net"
	"net/rpc"
	"sync"
)

type SumInput struct {
	UpTo int
}
type SumOutput struct {
	Result int
}
type RpcServer struct {
}

func (s *RpcServer) Calculate(in *SumInput, out *SumOutput) error {
	for i := 0; i < in.UpTo; i++ {
		out.Result += i
	}
	return nil
}

func main() {
	server := new(RpcServer)
	rpc.Register(server)
	sock, err := net.Listen("tcp", ":1234")
	if err != nil {
		panic(err)
	}

	go func() {
		for {
			conn, err := sock.Accept()
			if err != nil {
				panic(err)
			}
			go rpc.ServeConn(conn)
		}
	}()

	wg := &sync.WaitGroup{}
	wg.Add(100)
	for i := 0; i < 100; i++ {
		go func(i int) {
			client, err := rpc.Dial("tcp", "127.0.0.1:1234")
			if err != nil {
				panic(err)
			}
			rpcOut := &SumOutput{}
			err = client.Call("RpcServer.Calculate", &SumInput{100000000}, rpcOut)
			if err != nil {
				panic(err)
			}
			fmt.Println("Got reply: ", rpcOut, i)
			wg.Done()
		}(i)
	}
	wg.Wait()
}

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。

GOMAXPROCS=8 go run rpctest.go

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

export GOMAXPROCS=8

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

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

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

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?

export GOMAXPROCS=8

Normally I set this in program using the runtime module

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:

确定