Skip to content

Commit

Permalink
pythongh-127085: fix memoryview->exports race condition.
Browse files Browse the repository at this point in the history
  • Loading branch information
LindaSummer committed Nov 29, 2024
1 parent 3afb639 commit c7872cd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Lib/test/test_free_threading/test_memoryview.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import multiprocessing.shared_memory
from threading import Thread
import unittest

from test.support import threading_helper


class TestBase(unittest.TestCase):
pass


def do_race():
"""Repeatly access the memoryview for racing."""
n = 100

obj = multiprocessing.shared_memory.ShareableList("Uq..SeDAmB+EBrkLl.SG.Z+Z.ZdsV..wT+zLxKwdN\b")
threads = []
for _ in range(n):
threads.append(Thread(target=obj.count, args=(1,)))

for t in threads:
t.start()

for t in threads:
t.join()

del obj


@threading_helper.requires_working_threading()
class TestMemoryView(TestBase):
def test_racing_getbuf_and_releasebuf(self):
do_race()

if __name__ == "__main__":
unittest.main()
4 changes: 4 additions & 0 deletions Objects/memoryobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1589,7 +1589,9 @@ memory_getbuf(PyObject *_self, Py_buffer *view, int flags)


view->obj = Py_NewRef(self);
Py_BEGIN_CRITICAL_SECTION(self);
self->exports++;
Py_END_CRITICAL_SECTION();

return 0;
}
Expand All @@ -1598,7 +1600,9 @@ static void
memory_releasebuf(PyObject *_self, Py_buffer *view)
{
PyMemoryViewObject *self = (PyMemoryViewObject *)_self;
Py_BEGIN_CRITICAL_SECTION(self);
self->exports--;
Py_END_CRITICAL_SECTION();
return;
/* PyBuffer_Release() decrements view->obj after this function returns. */
}
Expand Down

0 comments on commit c7872cd

Please sign in to comment.