我真正需要的是便攜式比較和打印* 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