我真正需要的是便携式比较和打印* nix pthread标识符(pthread_t)。 pthread_equal函数存在比较两个线程ID的相等性,但它不可能与运算符< < => =>(可移植我的意思当然),因为在某些实现pthread_t是一个指向结构的指针。所以我找到了我想分享和讨论它的便携性的解决方案。便携式打印和比较pthread_t
假设我们有thred_id类包装器,它应该少于可比,平等可比,当然可打印。我在做模板类有两个偏特 - 一个指针和一个算术类型
template <typename T, bool A = is_arithmetic<T>::value>
struct hash
{
static unsigned long calculate(T thread_id)
{
return hash<T*, A>::calculate(&thread_id);
}
};
template <typename T>
struct hash<T*, false>
{
static unsigned long calculate(T* thread_id)
{
std::size_t hash = 0;
if (char* data = reinterpret_cast<char*>(thread_id))
{
for (int i = 0; i < sizeof(T); ++i)
{
hash = (hash << 6)^(hash >> 26)^data[i];
}
}
return hash;
}
};
template <typename T>
struct hash<T, true>
{
static unsigned long calculate(T thread_id)
{
return static_cast<unsigned long>(thread_id);
}
};
那么它是怎样工作的。如果我们需要比较两个线程ID,我们只是简单地调用
pthread_equal(tid1, tid2);
但对于运营商<我们使用哈希比较
hash<pthread_t>::calculate(tid1) < hash<pthread_t>::calculate(tid2)
所以这里
如果pthread_t
作为指针实现,那么我们将为指出的对象计算散列值。
如果是算术类型,那么我们将尝试将其转换为无符号整型。
如果它是作为结构实现的 - 我们将计算结构对象本身的哈希值。
哈希值将仅用于运算符较少和线程ID输出。
您对此有何看法?这种解决方案的便携性如何,还有什么更好的呢?
谢谢大家。
为什么你想强制执行一个固有的无法编辑的命令?你试图完成什么概念? – FooF 2013-07-12 04:53:19