线程本地存储在其他地方使用吗?

发布于 2024-08-12 04:15:46 字数 63 浏览 4 评论 0原文

除了使全局变量和静态变量成为线程本地变量之外,线程本地存储是否在其他地方使用?它在我们编写的任何新代码中有用吗?

Is thread local storage used anywhere else other than making global and static variables local to a thread?Is it useful in any new code that we write?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

余生再见 2024-08-19 04:15:47

TLS 在新代码中肯定有用。如果您想要一个特定于每个线程的全局变量(例如 C/C++ 中的 errno),那么线程本地存储就是您的最佳选择。

TLS can certainly be useful in new code. If you ever want a global variable which needs to be specific to each thread, (like errno in C/C++), thread-local-storage is the way to go.

笨笨の傻瓜 2024-08-19 04:15:47

线程特定的单例对象?一个多线程 Web 服务器,其中每个线程处理一个请求,很可能存在一些 TLS 数据(例如请求 URL 或一些数据库连接,本质上是一些在请求处理期间的任何时候需要使用的资源) )以便在需要时可以在代码中的任何位置轻松访问它们。

Thread specific singleton objects? A multi-threaded web server where each thread is handling one request, there is quite a good amount of possibility of some TLS data (like request URL or some database connections, essentially some resources intended to be used at any point during request handling if required) so that they can be easily accessed anywhere in the code when required.

审判长 2024-08-19 04:15:47

如今,errno 通常被放入线程本地存储中。

在某些情况下(例如:需要启动代码的 DLL 之类的共享库),使用线程本地存储可能会出现问题。

These days errno is typically put in thread-local storage.

There are some situations (eg: shared libraries like DLLs that require startup code) where using thread-local storage can be a problem.

枯寂 2024-08-19 04:15:47

我只需要它来进行线程特定的错误处理和优化(在 C 语言中):

__thread int cpfs_errno;
static __thread struct Cpfs *g_cpfs;

在这个示例中,这使我无需通过数十个函数传递 struct Cpfs * 的上下文指针,而在这些函数中它永远不会传递变化。

I've only needed it for thread-specific error handling, and optimization (in C):

__thread int cpfs_errno;
static __thread struct Cpfs *g_cpfs;

In this example, this saves me passing a context pointer of struct Cpfs * through dozens of functions in which it never changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文