如何内核知道什么是当前线程? [英] How does the kernel know what is the current thread?

查看:176
本文介绍了如何内核知道什么是当前线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释这里我的code 这个片段拍摄从Linux内核?

  / *
  *如何从C获得线程信息结构
 * /
 静态内嵌结构的thread_info * current_thread_info(无效)__attribute_const__; 静态内嵌结构的thread_info * current_thread_info(无效)
 {
        注册无符号长SP ASM(SP);
        返程(结构的thread_info *)(SP&安培;〜(THREAD_SIZE - 1));
}

问题:


  1. 是什么 __ __ attribute_const

  2. 这是什么呢注册无符号长SP ASM(SP);

  3. 为什么(结构的thread_info *)(SP&安培;〜(THREAD_SIZE - 1)); 返回
    指针结构?


解决方案

  1. 属性常量表示返回的指针将保持不变为节目的持续时间。在实践中,这是真实的,只有在一个线程的范围,但我想不出任何情况下编译器甚至会尝试优化线程之间的访问。


  2. 使用注册 ASM(SP)结合称为硬件寄存器变量 SP ,即当前堆栈指针。以此方式,code没有被写入在汇编直接访问该寄存器


  3. THREAD_SIZE是一个常量,这就给分配给线程堆栈的内存量。我认为它总是必须是2的幂,例如8千字节可能是一个典型值。

    这位前pression 〜(THREAD_SIZE - 1)则给出了摆脱实际堆栈地址的位掩码。对于8 KB的堆栈,这将是 0xffffe000

    通过采取位与堆栈指针的值,我们得到分配给栈的最低地址。在此架构中,线程信息存储在那里。这简直是​​一个设计决策,他们也可以使用其他一些地方存储的信息。

    堆栈指针是获得线程信息,因为每个线程总会有它自己的堆栈是有用的。


Can someone please explain me this snippet of code here taken from linux kernel?

/*
  * 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));
}

Questions:

  1. what is __attribute_const__ ?
  2. what does this do register unsigned long sp asm ("sp");
  3. why (struct thread_info *)(sp & ~(THREAD_SIZE - 1)); return a pointer to the struct?

解决方案

  1. Attribute const means that the returned pointer will remain the same for the duration of the program. In practice, this is true only in the scope of the one thread, but I can't think of any situation where a compiler would even try to optimize accesses between threads.

  2. Using register and asm("sp") binds a variable to the hardware register called sp, i.e. current stack pointer. This way the code does not have to be written in assembler to access this register directly.

  3. THREAD_SIZE is a constant, which gives the amount of memory allocated for the thread's stack. I assume that it always has to be a power of 2, e.g. 8 kilobytes might be a typical value.

    The expression ~(THREAD_SIZE - 1) then gives a bitmask for getting rid of the actual stack address. For 8 kB stack, it would be 0xffffe000.

    By taking a bitwise and with the stack pointer value, we get the lowest address allocated for the stack. On this architecture, the thread information is stored there. This is simply a design decision, they could have used some other place for storing the information.

    The stack pointer is useful for getting the thread information because each thread will always have its own stack.

这篇关于如何内核知道什么是当前线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆