Skip to content

Commit a4aec12

Browse files
Merge pull request #106 from SpecificProtagonist/master
Fixed Editor.__del__() crashes when there are still blocks in the buffer (#68)
2 parents 839ac5e + 857d5a7 commit a4aec12

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/gdpc/editor.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import random
1010
from concurrent import futures
1111
import logging
12+
import atexit
13+
import weakref
1214

1315
import numpy as np
1416
from glm import ivec3
@@ -76,16 +78,16 @@ def __init__(
7678
self._worldSlice: Optional[WorldSlice] = None
7779
self._worldSliceDecay: Optional[np.ndarray] = None
7880

81+
ref = weakref.ref(self)
82+
83+
# Use a lambda to allow unregistering only one instance
84+
self._cleanup = lambda: cleanup_at_exit(ref)
85+
atexit.register(self._cleanup)
86+
7987

8088
def __del__(self):
8189
"""Cleans up this Editor instance"""
82-
# awaits any pending buffer flush futures and shuts down the buffer flush executor
83-
self.multithreading = False
84-
# Flush any remaining blocks in the buffer.
85-
# This is purposefully done *after* disabling multithreading! This __del__ may be called at
86-
# interpreter shutdown, and it appears that scheduling a new future at that point fails with
87-
# "RuntimeError: cannot schedule new futures after shutdown" even if the executor has not
88-
# actually shut down yet. For safety, the last buffer flush must be done on the main thread.
90+
atexit.unregister(self._cleanup)
8991
self.flushBuffer()
9092

9193

@@ -594,3 +596,10 @@ def pushTransform(self, transformLike: Optional[TransformLike] = None):
594596
yield
595597
finally:
596598
self.transform = originalTransform
599+
600+
# Flush buffers if the system is shutting down.
601+
# Do this via an atexit handler instead of the destructor because it needs
602+
# to run before necessary modules are torns down.
603+
def cleanup_at_exit(ref: weakref.ref):
604+
if obj := ref():
605+
obj.flushBuffer()

0 commit comments

Comments
 (0)