我認爲,對於設定的線程數計算tail
的最大值,當沒有問題時,即當tail mod num_threads
爲0
時最大值爲tail
。然後如果tail
成功它,設置尾0
在構造我確定tail
for(unsigned i = UINT32_MAX; ; --i) // UINT32_MAX - max unsigned type value
if(i % size == 0)//size - max number of concurrent threads
{
max_tail = i;
break;
}
一個最大數,並在lock
方法我檢查它
unsigned max = max_tail;//otherwise, may overwrite max_tail
tail.compare_exchange_strong(max, 0);
全碼(C + +17)
class arr_lock
{
std::atomic<unsigned> tail;
static thread_local unsigned slotInd;
bool* flag;
unsigned size;//max number of concurrent threads
static constexpr size_t L1_cache = std::hardware_destructive_interference_size;
static constexpr size_t mult = L1_cache/sizeof(bool);
unsigned max_tail;
public:
arr_lock(unsigned size_) :
tail(0),
size(size_),
{
unsigned arr_size = mult * size;//padded for disable false sharing
flag = new bool[arr_size];
for(unsigned i = 0; i < arr_size; ++ i)
flag[i] = false;
flag[0] = true;
for(unsigned i = UINT32_MAX; ; --i)
if(i % size == 0)
{
max_tail = i;
break;
}
}
~arr_lock()
{
delete [] flag;
}
void lock()
{
unsigned max = max_tail;//otherwise, may overwrite max_tail
tail.compare_exchange_strong(max, 0);
unsigned slotInd = tail.fetch_add(1) % size;
unsigned ind = mult * slotInd;
while(!flag[ind]);
}
void unlock()
{
flag[mult * slotInd] = false;
flag[mult * (slotInd + 1) % (mult * size)] = true;
}
};
thread_local unsigned arr_lock::slotInd = 0;
這是如何遠程回答題? – Makoto
我根本沒注意,沒有粘貼評論,爲什麼要-1? –
你怎麼知道OP使用C?我不清楚他們在說什麼語言。 – Makoto