DeaD_EyE

is the locking broken in free threaded python version?

May 9th, 2026
5,186
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # try this with Python 3.15.0b1 and 3.15.0b1t
  2. # the freethreaded version looses results
  3. # if time.sleep(0) is removed, it's even worse
  4. # the non-freethreaded version does not have this issue
  5.  
  6.  
  7. import time
  8. from threading import Thread, synchronized_iterator
  9. from itertools import batched
  10.  
  11. @synchronized_iterator
  12. def numbers(n):
  13.     for x in range(n):
  14.         yield x
  15.  
  16. def consume(iterable, results):
  17.     numbers_append = results.append
  18.     for item in iterable:
  19.         numbers_append(item)
  20.         time.sleep(0)
  21.  
  22. def is_ok(numbers):
  23.     for batch in batched(numbers, 2):
  24.         if len(batch) == 2:
  25.             last, current = batch
  26.         else:
  27.             # handling odd length of numbers
  28.             last, current = current, batch[0]
  29.  
  30.         if last + 1 != current:
  31.             return False
  32.  
  33.     return True
  34.  
  35.  
  36. THREADS = 2
  37. success = 0
  38. errors = 0
  39. all_results = []
  40.  
  41. for try_number in range(100):
  42.     print(f"Try number: {try_number + 1}")
  43.     results = []
  44.     all_results.append(results)
  45.     gen = numbers(1_001)
  46.     threads = [Thread(target=consume, args=(gen, results)) for _ in range(THREADS)]
  47.     for t in threads:
  48.         t.start()
  49.     for t in threads:
  50.         t.join()
  51.  
  52.     if is_ok(results):
  53.         success += 1
  54.     else:
  55.         errors += 1
  56.  
  57. print(f"{success} times success and {errors} errors")
Advertisement