在C / C ++(多线程)中实现线程本地存储(TLS) [英] Implementation of Thread-local storage (TLS) in C/C++ (multithreading)

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

问题描述

我试图理解线程本地存储(TLS)类型的实现。可在 C ++ 11 中作为 thread_local 关键字或 C as __ thread 关键字。这篇维基百科文章说:

I am trying to understand the implementation of Thread-local storage (TLS) type. Available in C++11 as thread_local keyword or in C as __thread keyword. This wikipedia article says:


有时候,希望两个线程引用相同的
静态或全局变量,实际上是指不同的内存
位置,从而使变量线程本地化,规范
示例是C错误代码变量 errno

Sometimes it is desirable that two threads referring to the same static or global variable are actually referring to different memory locations, thereby making the variable thread-local, a canonical example being the C error code variable errno.

这用于使线程中的 static 全局变量变量,以便其他线程无法访问它们。

This is used for making static or global variables local to the threads, so that the other threads can't access them.

我的问题是这些变量是如何存储在内存中的,以便它成为线程的本地?

这些都是固有的全局/静态变量,什么阻止其他线程访问它们?

推荐答案

TLS是作为每个线程对象中的数据数组实现的。每个线程对象都有自己的数组本地副本,每个数组大小相同。当使用TLS声明一个全局/静态变量时,它与这些数组的索引相关联(这就是编译器/操作系统知道要分配多少个数组槽)。因此,当你在运行时访问变量时,你实际上正在访问访问变量的线程上下文的数据数组中的相关插槽。

TLS is implemented as a data array within each thread object. Each thread object has its own local copy of the array, and each array is the same size. When you declare a global/static variable as using TLS, it is associated with an index into those arrays (that is how the compiler/OS knows how many array slots to allocate). Thus, when you access the variable at runtime, you are really accessing the associated slot in the data array of the thread context that is accessing the variable.

TLS可能是

TLS在Windows上使用Win32 API实现 TlsAlloc() TlsGetValue() TlsSetValue() code> TlsFree()函数。以下是其工作原理的概述:主题本地存储

TLS is implemented on Windows using the Win32 API TlsAlloc(), TlsGetValue(), TlsSetValue(), and TlsFree() functions. Here is an overview of how it works: Thread Local Storage

以下是TLS在Linux上的工作原理: ELF处理线程本地存储

Here is an overview of how TLS works on Linux: ELF Handling For Thread-Local Storage

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

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