grpc python在客户端和服务器上支持多线程

问题描述:

我想知道grpc python支持多线程吗?请分享一些参考. 我已经在单线程中编写了代码,但不知道如何在多线程中编写.

I want to know Is grpc python support multithreading? please share some reference. I have written the code in the single thread but don't know how to write in multithread.

gRPC Python确实在客户端和服务器上都支持多线程.对于服务器,您将使用线程池创建服务器,因此默认情况下为多线程.对于客户端,您可以创建一个通道并将其传递给多个Python线程,然后为每个线程创建一个存根.另外,由于通道是用C而不是Python进行管理的,因此在同一过程中为同一服务器创建多个通道不会给您带来任何性能优势.

gRPC Python does support multithreading on both client and server. As for server, you will create the server with a thread pool, so it is multithreading in default. As for client, you can create a channel and pass it to multiple Python thread and then create a stub for each thread. Also, since the channel is managed in C instead of Python, create multiple channels to the same server in the same process won't give you any performance advantage.

import threading
import grpc

def worker(channel):
    stub = your_pb2_grpc.YourStub(channel)
    ...YOUR WORK WITH STUB

channel = grpc.insecure_channel(<YOUR PORT>)
your_thread = threading.Thread(target=worker, args=(channel,))
your_thread.start()

此外,如果您打算使用多处理而不是多线程,则可以在此处引用 https://github.com/grpc/grpc/issues/16001 https ://github.com/grpc/grpc/blob/master/doc/fork_support.md .

Also, if you intent to use multiprocessing instead of multithreading, you can reference here https://github.com/grpc/grpc/issues/16001 and https://github.com/grpc/grpc/blob/master/doc/fork_support.md.