Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - Do I need to call Channel.close() when my process exits?

I am using gRPC in a Python script, and most of my code is wrapped in this:

def main():
    with grpc.insecure_channel(address) as channel:
        ...

I am trying to reduce the indentation depth of the code, and wondering if we can drop the with. (One can argue if this is just vanity, or useful because it becomes more readable, but let's go with it for a second. I'm just curious about the behavior of gRPC here.) I would replace it with an explicit call to .close, however this script is likely to be stopped with Ctrl+C most of the time so that wouldn't get called.

How bad is it if the channel doesn't get closed? My process is exiting anyway, so it won't leak memory. Will it clog a connection slot on the server? For how long? This script is going to be called rarely, manually, and not multiple instances at the same time.

question from:https://stackoverflow.com/questions/65843011/do-i-need-to-call-channel-close-when-my-process-exits

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your Operating System should close connections when the process is killed, and otherwise there are configurable timeouts/deadlines that are generally wise to use, so it's unlikely that you'll leak resources. It's not recommended to exit without closing the channel, however.

One solution to your nesting problem would be to extract your code into a separate function:

def do_work(channel):
  pass

def main():
  with grpc.insecure_channel(address) as channel:
    do_work(channel)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...