#!/usr/bin/env python

from AdaptiveLoadController import AdaptiveLoadController

import time
class AdaptiveSleeper:
	"""A mixin class you can inherit in your thread-derived classes. Whenever you want your thread to sleep an optimum time to maintain the target load specified in the AdaptiveLoadController, call self.sleep()."""
	
	def __init__(self):
		pass

	def sleep(self):
		self.__do_sleep()

	def __do_sleep(self):
		has_slept_for = 0.0
		while has_slept_for < AdaptiveLoadController.throttle_ms:
			difference = AdaptiveLoadController.throttle_ms - has_slept_for
			if difference <= 0.0: break
			now_sleep_for = min(AdaptiveLoadController.sleeper_granularity,difference)
			time.sleep(float(now_sleep_for))
			has_slept_for = has_slept_for + now_sleep_for

