簡體   English   中英

多線程代碼:矢量 <bool> 迭代器不兼容

[英]Multithreaded code: vector<bool> iterators incompatible

以下代碼旨在返回尚未使用的最小非負整數。 從多個線程調用它。 如果樣式看起來有些奇怪,那是因為此類旨在駐留在僅標頭庫中。

class Unique
{
public:
    static unsigned int getIndex()
    {
        boost::unique_lock<boost::mutex> lock(get().mutex);
        unsigned int index = 0;
        while (index < get().valueInUse.size() && get().valueInUse[index])
            index++;
        if (index == get().valueInUse.size()) get().valueInUse.push_back(true);
        get().valueInUse[index] = true;
        return index;
    }
    static void releaseIndex(unsigned int index)
    {
        boost::unique_lock<boost::mutex> lock(get().mutex);
        get().valueInUse[index] = false;
    }
private:
    static Unique &get()
    {
        static Unique s;
        return s;
    }
    boost::mutex mutex;
    std::vector<bool> valueInUse;
};

此代碼有時會出現調試時問題:

vector<bool> iterators incompatible

堆棧跟蹤顯示在push_back()處發生的問題- index為零。 STL實現似乎認為它是在vector<bool>的另一個實例的end()處插入的。 使用Visual Studio 2010 Express。

有任何想法嗎? 這段代碼是線程安全的,不是嗎?

除非您保證在創建任何線程之前調用一次get函數,否則它肯定不是線程安全的。 而且由於您使用get調用獲取互斥量來保護其余代碼,因此肯定可以在其中得到一些意外結果。

std::vector<bool>專門用於每個布爾位,因此確實會更改迭代結果(我相信它使用代理對象)。 您是否嘗試過使用deque而非vector來進行測試?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM