找到第一个位集并原子地取消它

时间:2015-10-09 18:41:01

标签: optimization locking bit-manipulation atomicity

我正在寻找以下代码行的说明(x86机器)或优化:

lock()
int x = ffs(words); // find first bit that set
long words = unset(x, words); // unset the bit "x" in "words"
unlock()

我不知道如何在没有锁定的情况下这样做。

1 个答案:

答案 0 :(得分:0)

如果words是无符号类型,那么非原子计算可以按如下方式完成:

words &= ~-words;

或等同地

words &= words - 1;

这是有效的,因为在-words中(假设2的补码,无符号类型必须使用),最低有效值1和它右边的所有0都不变,而左边的所有位都是最不重要的1是倒置的。因此words & ~-wordswords相同,除了最不重要的1。

但是,为了以原子方式执行此操作,您需要使用问题中指示的锁,或者您需要围绕原子比较和交换进行自旋循环。