2012-06-30 56 views
2

我知道如何解決n皇后拼圖,使用回溯和遞歸。使用pthreads解決N皇后拼圖

我在想如何使用多線程來優化它。

我想用p - 線程。

基本上我無法理解頂端應用線程的位置,以及在哪裏加入線程。

由於這是遞歸,我也無法理解線程在這裏如何工作。

-

感謝

阿洛克氪。

+0

我讀的書籍爲好,但急於找到方法。此外,我無法瞭解多線程如何與回溯和遞歸一起工作,它會真正優化嗎? –

+3

它可能。或者可能會讓事情變得很慢。這取決於很多事情,包括你如何寫它。總之,看一下英特爾的這篇文章,它並行地解決了您的問題 - http://software.intel.com/zh-cn/articles/getting-code-ready-for-parallel-execution-with-intel-parallel -composer/ – 2012-06-30 03:30:35

+1

其實最終的答案是否定的,它不會優化,因爲它是一個不規則的問題,遞歸地執行並且在回溯時同步會導致負載不平衡。因此,它是上述參考資料中Cilk解決方案的一個很好的例子,它將通過工程量測來平衡負載。 (這正是Cilk基準測試一直包含此問題的原因) –

回答

3

一種方法是使用隊列將每個擴展放入隊列中,而不是進行遞歸。有一個流行的擴展和它的工作線程池:

create a state with an empty board and put it into the queue 
create N threads with the following function 

線程函數:

while not done: 
    1) pop a state S from the queue (use locks), if queue is empty, 
    wait on a semaphore until there is an S 
    2) expand state S 
    2a) if S has feasible children then put them into the queue 
     except for one state SS, call it S and goto 2 
    (also signal the semaphore) 
    2b) if S has no feasible children goto 1 
end while 

您可以修改此不同的算法

+0

使用pthreads,您可能會使用條件變量而不是信號量在步驟1中等待。 – caf