简体   繁体   English

将地址和bool存储在一个单词中,以获得无锁双链表

[英]Store an address and a bool in one word for lock-free doubly linked list

I am reading some paper for lock-free doubly linked list. 我正在阅读一些关于无锁双链表的文章。 In these papers, they store an address to next and prev node and a flag in one word(int). 在这些论文中,它们将地址存储到next和prev节点,并在一个单词(int)中存储一个标志。

Is it because in 32-bit architectures all addresses are aligned in 4 byte boundaries so all address are multiple of 4? 是因为在32位架构中,所有地址都以4字节边界对齐,因此所有地址都是4的倍数?

and if the reason is what i say is this code ok? 如果我说的原因是这个代码好吗?

const int dMask = 1;
const int pMask = ~dMask;

int store(void* pPointer, bool pDel)
{
    return reinterpret_cast<int>(pPointer) | (int)pDel;
}

void load(int pData, void** pPointer, bool* pDel)
{
    *pPointer = reinterpret_cast<void*>(pData & pMask);
    *pDel = pData & dMask;
}

And another question: Do in other platforms such as Android mobile devices, above idea is correct? 还有一个问题:在Android移动设备等其他平台上,上述想法是否正确?

You're more or less correct. 你或多或少是正确的。 It's a common space optimization in very low level code. 这是非常低级代码中的常见空间优化。 It is not portable. 便携。 (You could make it slightly more portable by using intptr_t instead of int .) (通过使用intptr_t而不是int可以使它更具可移植性。)

Also, of course, the alignment only holds for pointers to more complex types; 当然,对齐仅适用于指向更复杂类型的指针; a char* won't necessarily be aligned. char*不一定是对齐的。 (The only times I've seen this used is in the implementation of memory management, where all of the blocks involved are required to be aligned sufficiently for any type.) (我见过的唯一一次是在内存管理的实现中,所涉及的所有块都需要对任何类型进行充分对齐。)

Finally, I'm not sure what the authors' of the paper are trying to do, but the code you post cannot be used in a multithreaded environment, at least on modern machines. 最后,我不确定作者的论文是做什么的,但是你发布的代码不能在多线程环境中使用,至少在现代机器上是这样。 To ensure that a modification in one thread is seen in another thread, you need to use atomic types, or some sort of fence or membar. 要确保在另一个线程中看到一个线程中的修改,您需要使用原子类型,或某种类型的fence或membar。

Addresses in most 32-bit architectures are not stored in 4-byte boundaries, but 1-byte. 大多数32位体系结构中的地址不存储在4字节边界中,而是存储在1字节中。 They are read from memory at 4-byte (the typical word size) increments. 它们以4字节(典型字长)增量从存储器中读取。 Without seeing the code for this doubly linked list, it sounds like they are enforcing some rules for how the container will store data. 如果没有看到这个双向链表的代码,听起来他们正在对容器如何存储数据实施一些规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM