类线程安全的静态const char[]

static const char [] in class thread safe?

本文关键字:char const 静态 线程 安全      更新时间:2023-10-16

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;
}

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

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

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

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

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