Skip to content

Commit

Permalink
Using a thread pool to avoid TAsyncSocket.open block the event loop (#…
Browse files Browse the repository at this point in the history
…287)

* Using a thread pool to avoid TAsyncSocket.open block the event loop

* Compatible with Python3.6
  • Loading branch information
aisk authored Jul 4, 2024
1 parent 5b319bd commit c52cd9c
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions thriftpy2/contrib/aio/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@

from __future__ import absolute_import, division

import ssl
import asyncio
import errno
import os
import socket
import ssl
import struct
import sys
if sys.version_info >= (3, 7, 0):
from asyncio import get_running_loop
else:
from asyncio import _get_running_loop as get_running_loop

from thriftpy2.transport import TTransportException
from thriftpy2.transport._ssl import (
Expand All @@ -17,6 +21,7 @@
DEFAULT_CIPHERS
)


MAC_OR_BSD = sys.platform == 'darwin' or sys.platform.startswith('freebsd')


Expand Down Expand Up @@ -145,7 +150,11 @@ async def open(self):
if self.connect_timeout:
self.raw_sock.settimeout(self.connect_timeout)

self.raw_sock.connect(addr)
loop = get_running_loop()
# The raw_sock.connect may block the event loop if the target
# server is slow or unreachable. Using a thread pool to solve it
# as a quick and dirty way. See #270.
await loop.run_in_executor(None, lambda: self.raw_sock.connect(addr))

if self.socket_timeout:
self.raw_sock.settimeout(self.socket_timeout)
Expand Down

0 comments on commit c52cd9c

Please sign in to comment.