Linux的线程本地存储实现 [英] Linux's thread local storage implementation

查看:87
本文介绍了Linux的线程本地存储实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__thread Foo foo;

实际上如何解决"foo"?编译器是否用函数调用静默替换"foo"的每个实例? "foo"是否存储在相对于堆栈底部的某个位置,并且编译器将其存储为嘿,对于每个线程,此空间都位于堆栈底部附近,而foo存储为'距堆栈底部的偏移量x". ?

How is "foo" actually resolved? Does the compiler silently replace every instance of "foo" with a function call? Is "foo" stored somewhere relative to the bottom of the stack, and the compiler stores this as "hey, for each thread, have this space near the bottom of the stack, and foo is stored as 'offset x from bottom of stack'"?

推荐答案

有点复杂(此文档对其进行了详尽的解释),但实际上两者都不是.相反,编译器在可执行文件中放置一个特殊的.tdata节,其中包含所有线程局部变量.在运行时,将为每个线程创建一个新的数据段,并在(tread.tdata)节中创建一个数据副本,并且在运行时切换线程时,该段也会自动切换.

It's a little complicated (this document explains it in great detail), but it's basically neither. Instead the compiler puts a special .tdata section in the executable, which contains all the thread-local variables. At runtime, a new data section for each thread is created with a copy of the data in the (read-only) .tdata section, and when threads are switched at runtime, the section is also switched automatically.

最终结果是__thread变量与常规变量一样快,并且它们也不占用额外的堆栈空间.

The end result is that __thread variables are just as fast as regular variables, and they don't take up extra stack space, either.

这篇关于Linux的线程本地存储实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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