| 1 |
import random |
| 2 |
import unittest |
| 3 |
|
| 4 |
from functools import lru_cache |
| 5 |
from threading import Barrier, Thread |
| 6 |
|
| 7 |
from test.support import threading_helper |
| 8 |
|
| 9 |
@threading_helper.requires_working_threading() |
| 10 |
class TestLRUCache(unittest.TestCase): |
| 11 |
|
| 12 |
def _test_concurrent_operations(self, maxsize): |
| 13 |
num_threads = 10 |
| 14 |
b = Barrier(num_threads) |
| 15 |
@lru_cache(maxsize=maxsize) |
| 16 |
def func(arg=0): |
| 17 |
return object() |
| 18 |
|
| 19 |
|
| 20 |
def thread_func(): |
| 21 |
b.wait() |
| 22 |
for i in range(1000): |
| 23 |
r = random.randint(0, 1000) |
| 24 |
if i < 800: |
| 25 |
func(i) |
| 26 |
elif i < 900: |
| 27 |
func.cache_info() |
| 28 |
else: |
| 29 |
func.cache_clear() |
| 30 |
|
| 31 |
threads = [] |
| 32 |
for i in range(num_threads): |
| 33 |
t = Thread(target=thread_func) |
| 34 |
threads.append(t) |
| 35 |
|
| 36 |
with threading_helper.start_threads(threads): |
| 37 |
pass |
| 38 |
|
| 39 |
def test_concurrent_operations_unbounded(self): |
| 40 |
self._test_concurrent_operations(maxsize=None) |
| 41 |
|
| 42 |
def test_concurrent_operations_bounded(self): |
| 43 |
self._test_concurrent_operations(maxsize=128) |
| 44 |
|
| 45 |
def _test_reentrant_cache_clear(self, maxsize): |
| 46 |
num_threads = 10 |
| 47 |
b = Barrier(num_threads) |
| 48 |
@lru_cache(maxsize=maxsize) |
| 49 |
def func(arg=0): |
| 50 |
func.cache_clear() |
| 51 |
return object() |
| 52 |
|
| 53 |
|
| 54 |
def thread_func(): |
| 55 |
b.wait() |
| 56 |
for i in range(1000): |
| 57 |
func(random.randint(0, 10000)) |
| 58 |
|
| 59 |
threads = [] |
| 60 |
for i in range(num_threads): |
| 61 |
t = Thread(target=thread_func) |
| 62 |
threads.append(t) |
| 63 |
|
| 64 |
with threading_helper.start_threads(threads): |
| 65 |
pass |
| 66 |
|
| 67 |
def test_reentrant_cache_clear_unbounded(self): |
| 68 |
self._test_reentrant_cache_clear(maxsize=None) |
| 69 |
|
| 70 |
def test_reentrant_cache_clear_bounded(self): |
| 71 |
self._test_reentrant_cache_clear(maxsize=128) |
| 72 |
|
| 73 |
|
| 74 |
if __name__ == "__main__": |
| 75 |
unittest.main() |