c - 使用 'color' 定义对象的标志状态?

标签 c bit-manipulation status

我问这个问题是因为这不是我第一次看到这种编码实践,但从未见过任何关于其原因的评论:我正在浏览 Lua 的源代码,发现他们使用“颜色”(白色) ,黑色)来描述对象的状态。这是头文件 lgc.h 中的代码:

/*
** Layout for bit use in `marked' field:
** bit 0 - object is white (type 0)
** bit 1 - object is white (type 1)
** bit 2 - object is black
** bit 3 - for userdata: has been finalized
** bit 3 - for tables: has weak keys
** bit 4 - for tables: has weak values
** bit 5 - object is fixed (should not be collected)
** bit 6 - object is "super" fixed (only the main thread)
*/

#define WHITE0BIT   0
#define WHITE1BIT   1
#define BLACKBIT    2
#define FINALIZEDBIT    3
#define KEYWEAKBIT  3
#define VALUEWEAKBIT    4
#define FIXEDBIT    5
#define SFIXEDBIT   6
#define WHITEBITS   bit2mask(WHITE0BIT, WHITE1BIT)

#define iswhite(x)      test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
#define isblack(x)      testbit((x)->gch.marked, BLACKBIT)
#define isgray(x)   (!isblack(x) && !iswhite(x))

#define otherwhite(g)   (g->currentwhite ^ WHITEBITS)
#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS)

#define changewhite(x)  ((x)->gch.marked ^= WHITEBITS)
#define gray2black(x)   l_setbit((x)->gch.marked, BLACKBIT)

#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))

我已经在其他项目中看到了类似的东西(甚至使用了“红色”),但从未理解(也不关心)颜色和对象状态之间的概念联系是什么。有没有某种约定规定“白色”应该意味着“好”,而“黑色”、“坏”或类似的东西?有谁知道这种做法的起源是什么?

最佳答案

它的起源可能是white-gray-black吗?深度优先搜索?在此版本的算法中,白色顶点未被访问,灰色顶点在树向下的过程中已被访问,并且灰色顶点在返回的过程中变为黑色。

从评论中我认为这与垃圾收集有关?

关于c - 使用 'color' 定义对象的标志状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230698/

相关文章:

git - 为什么 .gitignore 中的目录仍然被 "git status"跟踪?

c - 将多个无符号字符数据从一个函数返回到另一个函数

c++ - 使用 std::bitset 或相同大小的基本类型?

c++ - 如何从文件中连续读取 N 个字节直到 EOF

Java打印整数与Integer.toHexString() : Different outputs

javascript - Yammer REST API 用于创建主题状态并获取主题 ID

c - 制作 libcurl CodeLite 项目

c++ - const关键字在编程中有什么好处?

c - 这个C代码有什么问题?

email - 每周向用户提供程序更新的最佳方式是什么?