dsij89625 2014-01-26 10:05
浏览 24
已采纳

为什么此RPC服务器无法扩展?

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条回答 默认 最新

  • douyulv6921 2014-01-26 10:17
    关注

    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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?