类const线程中的static const char []是否安全?

时间:2013-03-15 15:05:52

标签: c++ multithreading static const mutex

static const在类线程中是否安全?在下面的代码中,我有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;
}

2 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:3)

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

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

要显示数据争用条件,必须至少进行写操作