I have a Python module that's a bit buggy. Sometimes, the function calls will take forever or even segfault. It will be a long while before upstrean gets to fix this. I need to find a way to run the method ball()
with a time limit. Unfortunately, the suggestions from here won't help since the process is unresponsive. Any hints?
from contextlib import contextmanager
import signal
import math
import time
from meshpy.geometry import (
EXT_OPEN,
GeometryBuilder,
generate_surface_of_revolution,
)
from meshpy.tet import MeshInfo, build
# function that takes about 1min
def ball(h):
r = 3.0
polar_subdivision = int(math.pi / h)
dphi = math.pi / polar_subdivision
def truncate(val):
return 0 if abs(val) < 1e-10 else val
rz = [
[truncate(r * math.sin(i * dphi)), r * math.cos(i * dphi)]
for i in range(polar_subdivision + 1)
]
geob = GeometryBuilder()
radial_subdivision = int(2 * math.pi / h)
geob.add_geometry(
*generate_surface_of_revolution(
rz, closure=EXT_OPEN, radial_subdiv=radial_subdivision
)
)
mesh_info = MeshInfo()
geob.set(mesh_info)
build(mesh_info)
# time.sleep(20) # works
# from <https://stackoverflow.com/a/601168/353337>
class TimeoutException(Exception):
pass
@contextmanager
def time_limiter(seconds):
def signal_handler(signum, frame):
raise TimeoutException("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
with time_limiter(3):
ball(0.02)