我认为,对于设定的线程数计算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