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

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

问题描述

有人可以在这里向我解释这段代码吗 取自 linux 内核?

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

问题:

  1. 什么是__attribute_const__?
  2. 这是做什么的register unsigned long sp asm ("sp");
  3. 为什么 (struct thread_info *)(sp & ~(THREAD_SIZE - 1)); 返回一个指向结构的指针?
  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. 属性const 表示返回的指针在程序运行期间保持不变.实际上,这仅在一个线程的范围内是正确的,但我想不出任何情况下编译器甚至会尝试优化线程之间的访问.

  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.

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

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.

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

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.

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

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天全站免登陆