|
| 1 | +import unittest |
| 2 | + |
| 3 | +from threading import Thread |
| 4 | +from multiprocessing.dummy import Pool |
| 5 | +from unittest import TestCase |
| 6 | + |
| 7 | +from test.support import is_wasi |
| 8 | + |
| 9 | + |
| 10 | +NTHREADS = 6 |
| 11 | +BOTTOM = 0 |
| 12 | +TOP = 1000 |
| 13 | +ITERS = 100 |
| 14 | + |
| 15 | +class A: |
| 16 | + attr = 1 |
| 17 | + |
| 18 | +@unittest.skipIf(is_wasi, "WASI has no threads.") |
| 19 | +class TestType(TestCase): |
| 20 | + def test_attr_cache(self): |
| 21 | + def read(id0): |
| 22 | + for _ in range(ITERS): |
| 23 | + for _ in range(BOTTOM, TOP): |
| 24 | + A.attr |
| 25 | + |
| 26 | + def write(id0): |
| 27 | + for _ in range(ITERS): |
| 28 | + for _ in range(BOTTOM, TOP): |
| 29 | + # Make _PyType_Lookup cache hot first |
| 30 | + A.attr |
| 31 | + A.attr |
| 32 | + x = A.attr |
| 33 | + x += 1 |
| 34 | + A.attr = x |
| 35 | + |
| 36 | + |
| 37 | + with Pool(NTHREADS) as pool: |
| 38 | + pool.apply_async(read, (1,)) |
| 39 | + pool.apply_async(write, (1,)) |
| 40 | + pool.close() |
| 41 | + pool.join() |
| 42 | + |
| 43 | + def test_attr_cache_consistency(self): |
| 44 | + class C: |
| 45 | + x = 0 |
| 46 | + |
| 47 | + DONE = False |
| 48 | + def writer_func(): |
| 49 | + for i in range(3000): |
| 50 | + C.x |
| 51 | + C.x |
| 52 | + C.x += 1 |
| 53 | + nonlocal DONE |
| 54 | + DONE = True |
| 55 | + |
| 56 | + def reader_func(): |
| 57 | + while True: |
| 58 | + # We should always see a greater value read from the type than the |
| 59 | + # dictionary |
| 60 | + a = C.__dict__['x'] |
| 61 | + b = C.x |
| 62 | + self.assertGreaterEqual(b, a) |
| 63 | + |
| 64 | + if DONE: |
| 65 | + break |
| 66 | + |
| 67 | + self.run_one(writer_func, reader_func) |
| 68 | + |
| 69 | + def test_attr_cache_consistency_subclass(self): |
| 70 | + class C: |
| 71 | + x = 0 |
| 72 | + |
| 73 | + class D(C): |
| 74 | + pass |
| 75 | + |
| 76 | + DONE = False |
| 77 | + def writer_func(): |
| 78 | + for i in range(3000): |
| 79 | + D.x |
| 80 | + D.x |
| 81 | + C.x += 1 |
| 82 | + nonlocal DONE |
| 83 | + DONE = True |
| 84 | + |
| 85 | + def reader_func(): |
| 86 | + while True: |
| 87 | + # We should always see a greater value read from the type than the |
| 88 | + # dictionary |
| 89 | + a = C.__dict__['x'] |
| 90 | + b = D.x |
| 91 | + self.assertGreaterEqual(b, a) |
| 92 | + |
| 93 | + if DONE: |
| 94 | + break |
| 95 | + |
| 96 | + self.run_one(writer_func, reader_func) |
| 97 | + |
| 98 | + def run_one(self, writer_func, reader_func): |
| 99 | + writer = Thread(target=writer_func) |
| 100 | + readers = [] |
| 101 | + for x in range(30): |
| 102 | + reader = Thread(target=reader_func) |
| 103 | + readers.append(reader) |
| 104 | + reader.start() |
| 105 | + |
| 106 | + writer.start() |
| 107 | + writer.join() |
| 108 | + for reader in readers: |
| 109 | + reader.join() |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + unittest.main() |
0 commit comments