cpython/Lib/test/test_free_threading/test_methodcaller.py
Pieter Eendebak b0f278ff05
gh-127065: Make methodcaller thread-safe and re-entrant (GH-127746)
The function `operator.methodcaller` was not thread-safe since the additional
of the vectorcall method in gh-89013. In the free threading build the issue
is easy to trigger, for the normal build harder.

This makes the `methodcaller` safe by:

* Replacing the lazy initialization with initialization in the constructor.
* Using a stack allocated space for the vectorcall arguments and falling back
  to `tp_call` for calls with more than 8 arguments.
2024-12-11 10:06:07 -05:00

33 lines
815 B
Python

import unittest
from threading import Thread
from test.support import threading_helper
from operator import methodcaller
class TestMethodcaller(unittest.TestCase):
def test_methodcaller_threading(self):
number_of_threads = 10
size = 4_000
mc = methodcaller("append", 2)
def work(mc, l, ii):
for _ in range(ii):
mc(l)
worker_threads = []
lists = []
for ii in range(number_of_threads):
l = []
lists.append(l)
worker_threads.append(Thread(target=work, args=[mc, l, size]))
for t in worker_threads:
t.start()
for t in worker_threads:
t.join()
for l in lists:
assert len(l) == size
if __name__ == "__main__":
unittest.main()