如何使用不同的线程启动两个算法,只使用第一个算法的输出完成?

时间:2017-10-12 06:46:50

标签: python multithreading algorithm python-3.x python-multithreading

我有两种能够解决数独谜题的算法。第一种使用跳舞链接算法(一种递归回溯的形式),另一种使用约束传播,然后是递归回溯。

我想用自己的线程启动这两种算法,我只希望第一次完成输出。因为两者将具有相同的输出(或者至少两者都具有可接受的输出),所以我想从第一个开始完成并且杀死另一个线程的答案。

有时算法可能需要100多秒才能完成完美拼图的算法,但我们还没有发现一个谜题会使两种算法同时出现。

我是否需要将线程标记为守护进程?我使用以下代码得到答案,我只是担心它没有做我希望它做的事情。

编辑:在进一步阅读之后看起来像我可能实际上想要使用多处理而不是线程。我将测试两者,看看他们如何比较。

import threading
import time
import queue

from dlx import dlx_solve
from norvig import norvig_solve

# Test grids:
grid1 = '003020600900305001001806400008102900700000008006708200002609500800203009005010300'
grid2 = '4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......'
hard1 = '.....6....59.....82....8....45........3........6..3.54...325..6..................'

def solve(algo, grid, worker_queue, id, stop_event):
    while not stop_event.is_set():

        ans = algo(grid)

        if not stop_event.is_set():
            worker_queue.put((ans, id))

        break


# queue for workers
worker_queue = queue.Queue()

# indicator for other threads to stop
stop_event = threading.Event()

# run workers
threads = []
threads.append(threading.Thread(target=solve, args=(dlx_solve, grid1, worker_queue, 'dlx', stop_event)))
threads.append(threading.Thread(target=solve, args=(norvig_solve, grid1, worker_queue, 'norvig', stop_event)))


for thread in threads:
    thread.start()

# this will block until the first element is in the queue
first_finished = worker_queue.get()

print(first_finished)

0 个答案:

没有答案