1. import json
  2. import time
  3. import threading
  4. import queue
  5. class FormSubmissionSync:
  6. def __init__(self, resource_queue):
  7. self.resource_queue = resource_queue # Queue of form submissions
  8. self.lock = threading.Lock() # Lock for thread safety
  9. def worker(self):
  10. while True:
  11. try:
  12. form_submission = self.resource_queue.get(timeout=1) # Get submission, timeout after 1 sec
  13. self.process_submission(form_submission)
  14. self.resource_queue.task_done() # Signal task completion
  15. except queue.Empty:
  16. # No more submissions, exit worker
  17. break
  18. def process_submission(self, submission):
  19. # Simulate resource processing
  20. time.sleep(submission['processing_time'])
  21. print(f"Processed submission: {submission['id']}")
  22. def sync_resources(self, submissions):
  23. # Populate the queue with submissions
  24. for submission in submissions:
  25. self.resource_queue.put(submission)
  26. # Create and start worker threads
  27. num_workers = 4
  28. threads = []
  29. for _ in range(num_workers):
  30. thread = threading.Thread(target=self.worker)
  31. thread.daemon = True # Allow main thread to exit even if workers are running
  32. threads.append(thread)
  33. thread.start()
  34. # Wait for all submissions to complete
  35. self.resource_queue.join()
  36. # Wait for all threads to finish
  37. for thread in threads:
  38. thread.join()
  39. if __name__ == '__main__':
  40. # Example Usage
  41. submissions = [
  42. {'id': 1, 'data': 'data1', 'processing_time': 2},
  43. {'id': 2, 'data': 'data2', 'processing_time': 1},
  44. {'id': 3, 'data': 'data3', 'processing_time': 3},
  45. {'id': 4, 'data': 'data4', 'processing_time': 1},
  46. {'id': 5, 'data': 'data5', 'processing_time': 2},
  47. ]
  48. resource_queue = queue.Queue()
  49. sync = FormSubmissionSync(resource_queue)
  50. sync.sync_resources(submissions)
  51. print("All submissions processed.")

Add your comment