@@ -4997,6 +4997,42 @@ def test_shared_memory_pickle_unpickle_dead_object(self):
49974997 with self .assertRaises (FileNotFoundError ):
49984998 pickle .loads (pickled_sms )
49994999
5000+ def test_shared_memory_del_with_live_buffer (self ):
5001+ # gh-155003: Garbage collecting a SharedMemory must not release a
5002+ # buffer that is still in use, and must still close the file
5003+ # descriptor.
5004+ cases = {
5005+ 'buf' : lambda sms : sms .buf ,
5006+ 'cast' : lambda sms : sms .buf .cast ('i' ),
5007+ }
5008+ if c_int is not None :
5009+ # Holds a buffer on the memoryview object itself (as a NumPy
5010+ # array would), so releasing the memoryview fails, not just
5011+ # closing the mmap.
5012+ cases ['ctypes' ] = lambda sms : (c_int * 4 ).from_buffer (sms .buf )
5013+ for case , make_view in cases .items ():
5014+ with self .subTest (case = case ):
5015+ sms = shared_memory .SharedMemory (create = True , size = 16 )
5016+ name = sms .name
5017+ fd = sms ._fd
5018+ sms .buf [0 ] = 42
5019+ kept = make_view (sms )
5020+ with support .catch_unraisable_exception () as cm :
5021+ del sms
5022+ support .gc_collect ()
5023+ self .assertIsNone (cm .unraisable )
5024+ with memoryview (kept ) as mv , mv .cast ('B' ) as view :
5025+ self .assertEqual (view [0 ], 42 )
5026+ view [1 ] = 43
5027+ if shared_memory ._USE_POSIX :
5028+ with self .assertRaises (OSError ):
5029+ os .fstat (fd )
5030+ other = shared_memory .SharedMemory (name )
5031+ self .assertEqual (bytes (other .buf [:2 ]), b'\x2a \x2b ' )
5032+ other .unlink ()
5033+ other .close ()
5034+ del kept
5035+
50005036 @warnings_helper .ignore_fork_in_thread_deprecation_warnings ()
50015037 def test_shared_memory_across_processes (self ):
50025038 # bpo-40135: don't define shared memory block's name in case of
0 commit comments