我目前正在开发迭代深化搜索,希望根据时间停止。我的代码如下所示:
def __init__(self, name='Agent', time_limit_s=5):
self.name = name
self.time_limit_s = time_limit_s
self.stop_event = threading.Event()
def move(self, board):
'''
This method is called by the game engine to get the next move from the bot. It is time-limited,
and uses the update_best_move method to get the best move.
'''
# Perform the iterative deepening search
# Set up a shared variable to store the best result found
best_move = None
best_result_lock = threading.Lock()
# Set up a separate thread to run the search loop
search_thread = threading.Thread(target=self.run_search, args=(board, best_move, best_result_lock))
# Start the search thread and run the search
search_thread.start()
# Wait for the search thread to finish or raise a TimeoutException
search_thread.join(timeout=self.time_limit_s) # timeout does not end the execution, merely waits for this long
if search_thread.is_alive():
print('Thread still alive')
self.stop_event.set() # Set the stop event to signal the search thread to stop running
return best_move
def run_search(self, board, best_move, best_result_lock):
'''
This method is called by the iterative_deepening_search method to run the search loop.
'''
cur_best_move = None
depth = 1
try:
while not self.stop_event.is_set():
cur_best_move, done = self.update_best_move(board, depth, cur_best_move)
with best_result_lock: # set the value of best_move in thread safe manner
best_move = cur_best_move
if done or self.stop_event.is_set():
break
depth += 1
except TimeoutException:
print('Time limit reached')
with best_result_lock: # set the value of best_move in thread safe manner
best_move = cur_best_move
然而,以下情况不断发生:
时间限制:5秒
现在我们几乎用完了可用的 5 秒,但是因为 5 秒还没有过去,所以开始了另一个迭代
我们现在总共让 16 秒过去了,而不是 5 秒。你可以想象情况可能更糟。我如何调整我的代码,以便它在设置的
time_limit_s
秒后明确停止?很高兴解决方案。
我尝试使用
time
和 threading.Event() 来指示代码停止,但它一直在超过时间限制,如上所述。