繁体   English   中英

多线程环境中的函数错误

[英]Error with function in multithreaded environment

我的函数所做的是遍历布尔数组,并在找到设置为false的元素时将其设置为true。 该函数是我的内存管理器单例类中的一种方法,该方法返回指向内存的指针。 我遇到一个错误,我的迭代器似乎遍历并最终从头开始,我相信这是因为多个线程正在调用该函数。

void* CNetworkMemoryManager::GetMemory()
{
        WaitForSingleObject(hMutexCounter, INFINITE);

    if(mCounter >= NetConsts::kNumMemorySlots)
    {
       mCounter = 0;
    }

    unsigned int tempCounter = mCounter;

    unsigned int start = tempCounter;

    while(mUsedSlots[tempCounter])
    {
        tempCounter++;

        if(tempCounter >= NetConsts::kNumMemorySlots)
        {
            tempCounter = 0;
        }

        //looped all the way around
        if(tempCounter == start)
        {
            assert(false);
            return NULL;
        }
    }

    //return pointer to free space and increment

    mCounter = tempCounter + 1;
        ReleaseMutex(hMutexCounter);

    mUsedSlots[tempCounter] = true;
    return mPointers[tempCounter];
}

我的错误是断言在循环中断言。 我的问题是如何修复该函数,并且该错误是由多线程引起的吗?

编辑:添加了一个互斥锁来保护mCounter变量。 没变。 仍然发生错误。

我不能说错误是否是由多线程引起的,但是我可以说您的代码不是线程安全的。

您可以通过以下方式释放锁

ReleaseMutex(hMutexCounter);

然后访问tempCounter和mUsedSlots:

mUsedSlots[tempCounter] = true;
return mPointers[tempCounter];

两者都不是常量。 这是一场数据竞赛,因为您没有正确序列化对这些变量的访问。

更改为:

mUsedSlots[tempCounter] = true;
const unsigned int retVal = mPointers[tempCounter];
ReleaseMutex(hMutexCounter);
return retVal;

然后,至少您的代码是线程安全的,是否可以解决您无法解决的问题,请尝试一下。 在具有多核的机器上,由于数据竞争而发生的事情非常奇怪。

作为一般的最佳实践,我建议您查看一些C ++ 11同步功能,例如std::mutexstd::lock_guard ,这将使您免于自我攻击,因为std :: lock_guard会自动释放锁定,因此您不会忘记而且,在这种情况下,您不能无意间过早地这样做。 这也将使您的代码更具可移植性。 如果您还没有C ++ 11,请使用boost等价物。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM