C ++ Debug断言失败,使用Windows.h互斥

时间:2014-09-05 16:08:01

标签: c++ multithreading concurrency assertion

我遇到此代码导致的问题:

char KernelFS::mount(Partition* part) {
WaitForSingleObject(mutexFS,INFINITE);
int pos;
for(pos=0; pos<26; pos++)
    if(mountedPartitions[pos] == 0)
        break;

if(pos < 26) {

    mountedPartitions[pos] = part;
    bitVectors[pos] = new BitVector(part);
    fileEvidention[pos] = new ListHandler();

    openedFiles[pos] = 0;
    forbidOpening[pos] = false;

    ReleaseMutex(mutexFS);
    return intToChar(pos);
}
else {
    ReleaseMutex(mutexFS);
    return '0';
}

}

char KernelFS :: format(char part){

WaitForSingleObject(mutexFS,INFINITE);
forbidOpening[charToInt(part)] = true;
ReleaseMutex(mutexFS);

while(openedFiles[charToInt(part)]>0)
    WaitForSingleObject(unmountSem,INFINITE);


WaitForSingleObject(mutexFS,INFINITE);
//  write fresh bit vector to cluster 0 of partition
bitVectors[charToInt(part)]->formatBitVector();
openedFiles[charToInt(part)] = 0;
forbidOpening[charToInt(part)] = false;
delete fileEvidention;    //!!***!!
fileEvidention[charToInt(part)] = new ListHandler();

// some other stuff, irrelevant

ReleaseMutex(mutexFS);
return 1;

}

执行3个线程,1个被阻塞,2个正在运行此代码; 他们首先调用mount,然后格式化(每个都有自己的参数Partition对象,p1和p2)。 第一次调用mount时,它总是通过 - 然后在下一次调用mount / format中的任何一个运行线程中随机发生一个断言失败。

通常,它在线程1期间失败 - 它调用mount(..)完成它,然后调用format(...)并失败: delete fileEvidention [charToInt(pos)]; (在调试模式下,当我到达此指令时,即使我尝试使用F11,也会出现断言失败)

如果重要......这是初始化:

char KernelFS::firstLetter = 'A';                   //  'A' = 65
Partition* KernelFS::mountedPartitions[26] = {0};   //  init. no partitions are mounted
BitVector* KernelFS::bitVectors[26] = {0};          //  init. no partitions are mounted
bool KernelFS::forbidOpening[26] = {false};
long KernelFS::openedFiles[26] = {0};
ListHandler* KernelFS::fileEvidention[26] = {0};

HANDLE KernelFS::mutexFS = CreateMutex(0,0,0);
HANDLE KernelFS::unmountSem = CreateSemaphore(0,0,INFINITE,0);

之前我从来没有遇到过这个错误,我不知道如何调试这个,也不知道是什么导致它。 感谢您的帮助,提前。

编辑: 当我删除标记的代码行(并忽略内存泄漏)时,没有断言失败。这巫术是什么?

! :)

1 个答案:

答案 0 :(得分:0)

解决。应该 delete fileEvidention [charToInt(part)]; ......