我有安裝了英特爾並行工作室2013的Visual Studio 2012,所以我有英特爾TBB。C++ Intel TBB和Microsoft PPL,如何在並行循環中使用next_permutation?
說我有下面的代碼:
const int cardsCount = 12; // will be READ by all threads
// the required number of cards of each colour to complete its set:
// NOTE that the required number of cards of each colour is not the same as the total number of cards of this colour available
int required[] = {2,3,4}; // will be READ by all threads
Card cards[cardsCount]; // will be READ by all threads
int cardsIndices[cardsCount];// this will be permuted, permutations need to be split among threads !
// set "cards" to 4 cards of each colour (3 colours total = 12 cards)
// set cardsIndices to {0,1,2,3...,11}
// this variable will be written to by all threads, maybe have one for each thread and combine them later?? or can I use concurrent_vector<int> instead !?
int logColours[] = {0,0,0};
int permutationsCount = fact(cardsCount);
for (int pNum=0; pNum<permutationsCount; pNum++) // I want to make this loop parallel !!
{
int countColours[3] = {0,0,0}; // local loop variable, no problem with multithreading
for (int i=0; i<cardsCount; i++)
{
Card c = cards[cardsIndices[i]]; // accessed "cards"
countColours[c.Colour]++; // local loop variable, np.
// we got the required number of cards of this colour to complete it
if (countColours[c.Colour] == required[c.Colour]) // read global variable "required" !
{
// log that we completed this colour and go to next permutation
logColours[c.Colour] ++; // should I use a concurrent_vector<int> for this shared variable?
break;
}
}
std::next_permutation(cardsIndices, cardsIndices+cardsCount); // !! this is my main issue
}
什麼我計算多少次,我們將完成一個顏色,如果我們從現有的卡隨機挑選,而這通過每個去詳盡地做可能的排列和順序選擇,當顏色「完成」時,我們打破並進入下一個排列。請注意,我們有4種不同顏色的卡片,但紅色,綠色和藍色所需的卡片數量爲{2,3,4}。 2張紅牌足以完成紅色並且我們有4張可用,因此紅色比藍色更有可能完成,這需要全部4張牌被選中。
我想使這個for-loop並行,但我的主要問題是如何處理「卡」排列?如果我有4個線程,我可以把它分成4個不同的區域,並讓每個線程都通過它們。
如果我不知道機器的內核數量,並且我希望程序自動選擇正確的併發線程數,該怎麼辦?肯定有一種方法可以使用英特爾或微軟工具來做到這一點?
這是我的名片結構以防萬一:
struct Card
{
public:
int Colour;
int Symbol;
}
嗯..我不明白這個主意,但我可以看到你不關心我擁有的卡片。如果你不知道這些卡片,這個如何工作?在我的例子中,我有4種顏色的卡片,總共3種顏色,所以有12張卡片。我編輯了我的問題,以表明.. – 2013-04-27 13:22:38
我很在乎。在'f'函數中有一個'if',它檢查剩餘所需顏色的卡片數量。我以爲你可以自己填寫代碼。 – Ixanezis 2013-04-27 17:33:12
請看看完整的實現:http://ideone.com/9ibXaa – Ixanezis 2013-04-27 18:29:57