gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/grpc/Documentation/concurrency.md (about)

     1  # Concurrency
     2  
     3  In general, gRPC-go provides a concurrency-friendly API. What follows are some
     4  guidelines.
     5  
     6  ## Clients
     7  
     8  A [ClientConn][client-conn] can safely be accessed concurrently. Using
     9  [helloworld][helloworld] as an example, one could share the `ClientConn` across
    10  multiple goroutines to create multiple `GreeterClient` types. In this case,
    11  RPCs would be sent in parallel.  `GreeterClient`, generated from the proto
    12  definitions and wrapping `ClientConn`, is also concurrency safe, and may be
    13  directly shared in the same way.  Note that, as illustrated in
    14  [the multiplex example][multiplex-example], other `Client` types may share a
    15  single `ClientConn` as well.
    16  
    17  ## Streams
    18  
    19  When using streams, one must take care to avoid calling either `SendMsg` or
    20  `RecvMsg` multiple times against the same [Stream][stream] from different
    21  goroutines. In other words, it's safe to have a goroutine calling `SendMsg` and
    22  another goroutine calling `RecvMsg` on the same stream at the same time. But it
    23  is not safe to call `SendMsg` on the same stream in different goroutines, or to
    24  call `RecvMsg` on the same stream in different goroutines.
    25  
    26  ## Servers
    27  
    28  Each RPC handler attached to a registered server will be invoked in its own
    29  goroutine. For example, [SayHello][say-hello] will be invoked in its own
    30  goroutine. The same is true for service handlers for streaming RPCs, as seen
    31  in the route guide example [here][route-guide-stream].  Similar to clients,
    32  multiple services can be registered to the same server.
    33  
    34  [helloworld]: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_client/main.go#L43
    35  [client-conn]: https://godoc.org/google.golang.org/grpc#ClientConn
    36  [stream]: https://godoc.org/google.golang.org/grpc#Stream
    37  [say-hello]: https://github.com/grpc/grpc-go/blob/master/examples/helloworld/greeter_server/main.go#L41
    38  [route-guide-stream]: https://github.com/grpc/grpc-go/blob/master/examples/route_guide/server/server.go#L126
    39  [multiplex-example]: https://github.com/grpc/grpc-go/tree/master/examples/features/multiplex