1. import queue
  2. import threading
  3. import time
  4. import random
  5. class SandboxTask:
  6. def __init__(self, task_id, runtime):
  7. self.task_id = task_id
  8. self.runtime = runtime
  9. class SandboxQueue:
  10. def __init__(self, max_tasks=5):
  11. self.task_queue = queue.Queue(maxsize=max_tasks) # Limit the number of tasks
  12. self.lock = threading.Lock()
  13. def add_task(self, task):
  14. with self.lock:
  15. self.task_queue.put(task)
  16. def get_task(self):
  17. try:
  18. return self.task_queue.get(timeout=1) # Wait for a task, with a timeout
  19. except queue.Empty:
  20. return None # Return None if queue is empty
  21. class SandboxEnvironment:
  22. def __init__(self, memory_limit=1024, cpu_limit=2):
  23. self.memory_limit = memory_limit
  24. self.cpu_limit = cpu_limit
  25. def execute_task(self, task):
  26. print(f"Executing task {task.task_id} with runtime {task.runtime}")
  27. # Simulate task execution with random sleep
  28. sleep_time = random.uniform(0.1, task.runtime)
  29. time.sleep(sleep_time)
  30. print(f"Task {task.task_id} completed after {sleep_time:.2f} seconds.")
  31. class TaskExecutor(threading.Thread):
  32. def __init__(self, sandbox, task_queue):
  33. super().__init__()
  34. self.sandbox = sandbox
  35. self.task_queue = task_queue
  36. def run(self):
  37. while True:
  38. task = self.task_queue.get()
  39. if task is None:
  40. break # Exit thread if None is received
  41. self.sandbox.execute_task(task)
  42. self.task_queue.task_done() # Indicate task completion
  43. def main():
  44. # Define sandbox limits
  45. memory_limit = 1024 # MB
  46. cpu_limit = 2
  47. # Create sandbox environment
  48. sandbox = SandboxEnvironment(memory_limit=memory_limit, cpu_limit=cpu_limit)
  49. # Create task queue with a limit
  50. task_queue = SandboxQueue(max_tasks=3)
  51. # Create and start worker thread
  52. executor_thread = TaskExecutor(sandbox, task_queue)
  53. executor_thread.daemon = True # Allow main thread to exit even if worker is running
  54. executor_thread.start()
  55. # Add tasks to the queue
  56. tasks = [
  57. SandboxTask(1, 0.5),
  58. SandboxTask(2, 1.2),
  59. SandboxTask(3, 0.8),
  60. SandboxTask(4, 1.5),
  61. SandboxTask(5, 0.7),
  62. ]
  63. for task in tasks:
  64. task_queue.add_task(task)
  65. # Wait for all tasks to complete
  66. task_queue.join()
  67. print("All tasks completed.")
  68. if __name__ == "__main__":
  69. main()

Add your comment