我正在使用tpl并行执行数据。问题是,有时它会毫无理由地挂起来提供这样的输出:
The thread '<No Name>' (0x4aa4) has exited with code 0 (0x0).
The thread '<No Name>' (0x2bf4) has exited with code 0 (0x0).
The thread '<No Name>' (0x417c) has exited with code 0 (0x0).
The thread '<No Name>' (0x432c) has exited with code 0 (0x0).
The thread '<No Name>' (0x3ad0) has exited with code 0 (0x0).
The thread '<No Name>' (0x4440) has exited with code 0 (0x0).
The thread '<No Name>' (0x24e8) has exited with code 0 (0x0).
The thread '<No Name>' (0x3354) has exited with code 0 (0x0).
The thread '<No Name>' (0x4a30) has exited with code 0 (0x0).
程序仍然会执行,当我在visual studio中暂停它时,它会暂停我有ForEach的并行程序:
Parallel.ForEach
(
hold1.remainingHolds.ToArray(),
subSequence =>
{
//only if subsequence has 1 common substring
if (checkIfCommon(remainingSequence, subSequence.ToString()) == 1)
{
goDownLinkType2(subSequence.ToString().Split(','), 0,
(SuffixNode)hold1.childHolds[subSequence.ToString().Split(',')[0]]);
}
}
);
我不认为它是一个死锁,因为不存在可以有一个线程等待不同资源并且互相锁定的情况
它应该进入这个方法并且recursivley去一个后缀树,直到没有线程将任何对象添加到arraylist
Boolean flag = false;
public void goDownLinkType2
(string[] splittedString,
int index, SuffixNode currentNode)
{
Boolean writingFlag = false;
if (index == 2)
{
while(writingFlag == false)
{
while(flag == true)
{
//blocked
}
if (flag == false)
{
flag = true;
if(!secondChoiceResults.Contains
(currentNode.representingStance.SequenceOfHolds))
{
Console.WriteLine("new addition");
secondChoiceResults.Add
(currentNode.representingStance.SequenceOfHolds,
currentNode.representingStance);
}
flag = false;
writingFlag = true;
}
}
}
else
{
int nextIndex = index + 1;
goDownLinkType2
(splittedString,
nextIndex,
(SuffixNode)currentNode.childHolds[splittedString[nextIndex]]
);
}
}
答案 0 :(得分:1)
抛出'flag'变量并使用lock语句。使用此代码可以在您的关键部分中有多个线程(即一个线程即将设置flag = true而另一个线程只评估flag == false为true(btw将来使用!标志)< / p>
lock( obj )
{
// critical section here
}
obj只需要是对所有线程都可访问的对象的引用。
以下是我对您的代码的修改:
public void goDownLinkType2(string[] splittedString, int index, SuffixNode currentNode)
{
Boolean writingFlag = false;
if (index == 2)
{
while(writingFlag == false)
{
lock( this )
//while(flag == true)
//{
//blocked
//}
//if (flag == false)
{
//flag = true;
if (!secondChoiceResults.Contains(currentNode.representingStance.SequenceOfHolds))
{
Console.WriteLine("new addition");
secondChoiceResults.Add(currentNode.representingStance.SequenceOfHolds, currentNode.representingStance);
}
//flag = false;
writingFlag = true;
}
}
}
else
{
int nextIndex = index + 1;
goDownLinkType2(splittedString, nextIndex, (SuffixNode)currentNode.childHolds[splittedString[nextIndex]]);
}
}