gpt4 book ai didi

c - 内核如何知道当前线程是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:33:51 24 4
gpt4 key购买 nike

谁能解释一下这段代码 here取自 linux 内核?

/*
* how to get the thread information struct from C
*/
static inline struct thread_info *current_thread_info(void) __attribute_const__;

static inline struct thread_info *current_thread_info(void)
{
register unsigned long sp asm ("sp");
return (struct thread_info *)(sp & ~(THREAD_SIZE - 1));
}

问题:

  1. 什么是 __attribute_const__
  2. 这是做什么的 register unsigned long sp asm ("sp");
  3. 为什么 (struct thread_info *)(sp & ~(THREAD_SIZE - 1)); 返回一个指向结构的指针?

最佳答案

  1. 属性const 表示返回的指针在程序执行期间将保持不变。实际上,这仅在一个线程的范围内是正确的,但我想不出编译器会尝试优化线程间访问的任何情况。

  2. 使用registerasm("sp") 绑定(bind)一个变量到名为sp 的硬件寄存器,即当前堆栈指针.这样代码就不必用汇编语言来直接访问这个寄存器了。

  3. THREAD_SIZE 是一个常量,它给出了为线程堆栈分配的内存量。我假设它总是必须是 2 的幂,例如8 KB 可能是一个典型值。

    表达式 ~(THREAD_SIZE - 1) 然后给出了一个位掩码来去除实际的堆栈地址。对于 8 kB 堆栈,它将是 0xfffffe000

    通过按位取栈指针值,我们得到分配给栈的最低地址。在此体系结构上,线程信息存储在那里。这只是一个设计决定,他们本可以使用其他地方来存储信息。

    堆栈指针对于获取线程信息很有用,因为每个线程总是有自己的堆栈。

关于c - 内核如何知道当前线程是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12193281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com