| 189 | |
| 190 | |
| 191 | def test_memoize_not_thread_safe(): |
| 192 | class Counter(object): |
| 193 | def __init__(self, s): |
| 194 | self.val = s |
| 195 | |
| 196 | def inc(self): |
| 197 | self.val += 1 |
| 198 | return self.val |
| 199 | |
| 200 | @func.memoize(thread_safe=False) |
| 201 | def io_job(n): |
| 202 | time.sleep(0.1) |
| 203 | return Counter(n) |
| 204 | |
| 205 | def worker(n): |
| 206 | assert io_job(n).inc() == n + 1 |
| 207 | assert io_job(n).inc() == n + 2 |
| 208 | assert io_job(n*10).inc() == n*10 + 1 |
| 209 | assert io_job(n*10).inc() == n*10 + 2 |
| 210 | assert io_job(n).inc() == n + 3 |
| 211 | |
| 212 | threads = [] |
| 213 | for i in range(5): |
| 214 | threads.append(threading.Thread(target=worker, args=(i+1,))) |
| 215 | |
| 216 | st = time.time() |
| 217 | |
| 218 | for thread in threads: |
| 219 | thread.start() |
| 220 | for thread in threads: |
| 221 | thread.join() |
| 222 | |
| 223 | elapsed_time = time.time() - st |
| 224 | assert elapsed_time < 0.5 |
| 225 | |
| 226 | |
| 227 | def test_memoize_not_thread_safe_concurrent(): |