generators.py 917 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. pdf2image filename generators
  3. """
  4. import uuid
  5. import threading
  6. class ThreadSafeGenerator(object):
  7. """Wrapper around generator that protects concurrent access"""
  8. def __init__(self, gen):
  9. self.gen = gen
  10. self.lock = threading.Lock()
  11. def __iter__(self):
  12. return self
  13. def __next__(self):
  14. with self.lock:
  15. return next(self.gen)
  16. def threadsafe(f):
  17. """Decorator to make generator threadsafe. Fix #125"""
  18. def g(*a, **kw):
  19. return ThreadSafeGenerator(f(*a, **kw))
  20. return g
  21. @threadsafe
  22. def uuid_generator():
  23. """Returns a UUID4"""
  24. while True:
  25. yield str(uuid.uuid4())
  26. @threadsafe
  27. def counter_generator(prefix="", suffix="", padding_goal=4):
  28. """Returns a joined prefix, iteration number, and suffix"""
  29. i = 0
  30. while True:
  31. i += 1
  32. yield str(prefix) + str(i).zfill(padding_goal) + str(suffix)