我有安装了英特尔并行工作室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