5

static const's 在类线程中安全吗?在下面的代码中,我有trailingBytesForUTF8一个static const字符数组。可能有许多线程拥有自己的CConvertUTF类对象实例。trailingBytesForUTF8当多个线程同时访问同一个数组或任何其他线程问题时,是否会出现任何可变状态问题?另请注意,线程永远不会共享该类的相同对象实例CConvertUTF

// .h
class CConvertUTF final
{
    private:
        static const char trailingBytesForUTF8[256];
    public:
        bool IsLegalUTF8Sequence(const char *source, const char *sourceEnd);
        bool IsLegalUTF8(const char *source, int length);
};

// .cpp
const char CConvertUTF::trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

bool CConvertUTF::IsLegalUTF8Sequence(const char *source, const char *sourceEnd) {
    int length = trailingBytesForUTF8[*source]+1;
    if (source+length > sourceEnd) {
    return false;
    }
    return IsLegalUTF8(source, length);
}

bool CConvertUTF::IsLegalUTF8(const char *source, int length) {
    char a;
    const *char = source+length;
    switch (length) {
    default: return false;
    /* Everything else falls through when "true"... */
    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 2: if ((a = (*--srcptr)) > 0xBF) return false;

    switch (*source) {
        /* no fall-through in this inner switch */
        case 0xE0: if (a < 0xA0) return false; break;
        case 0xED: if (a > 0x9F) return false; break;
        case 0xF0: if (a < 0x90) return false; break;
        case 0xF4: if (a > 0x8F) return false; break;
        default:   if (a < 0x80) return false;
    }

    case 1: if (*source >= 0x80 && *source < 0xC2) return false;
    }
    if (*source > 0xF4) return false;
    return true;
}
4

2 回答 2

7

只读 (const) 变量在它们被销毁之前始终是线程安全的。由于静态对象仅在程序终止时被销毁,因此它们对程序的生命周期有益。

唯一的例外是具有mutable成员的对象,但这不适用于char数组。

于 2013-03-15T15:22:09.587 回答
3

任何指定为static const全局且只读的数据。

这意味着不受竞争条件的影响,因为没有人会修改数据。

要出现数据竞争条件,必须至少有写入操作

于 2013-03-15T15:24:46.920 回答