在c99中使用__thread
我想使用 __thread 存储类定义一些特定于线程的变量。但三个问题让我犹豫:
- 它真的是c99中的标准吗?或者更重要的是,编译器支持有多好?
- 变量会在每个线程中初始化吗?
- 非多线程程序是否将它们视为普通的旧全局变量?
I would like to define a few variables as thread-specific using the __thread storage class. But three questions make me hesitate:
- Is it really standard in c99? Or more to the point, how good is the compiler support?
- Will the variables be initialised in every thread?
- Do non-multi threaded programs treat them as plain-old-globals?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
回答您的具体问题:
__thread
变量在每个新线程中都以其初始化值开始。除了实现 C/POSIX 之外(例如 errno 等),在我看来,线程本地存储类实际上不是很有用。它几乎是避免以上下文指针或类似形式干净地传递必要状态的拐杖。您可能认为它对于解决像
qsort
这样不采用上下文指针的损坏接口很有用,但不幸的是,不能保证qsort
会调用比较函数在调用 qsort 的同一线程中。它可能会分解作业并在多个线程中运行它。对于大多数其他可以使用这种解决方法的接口也是如此。To answer your specific questions:
__thread
variables start out with their initialized value in every new thread.Outside of implementing C/POSIX (e.g.
errno
, etc.), thread-local storage class is actually not very useful, in my opinion. It's pretty much a crutch for avoiding cleanly passing around the necessary state in the form of a context pointer or similar. You might think it could be useful for getting around broken interfaces likeqsort
that don't take a context pointer, but unfortunately there is no guarantee thatqsort
will call the comparison function in the same thread that calledqsort
. It might break the job down and run it in multiple threads. Same goes for most other interfaces where this sort of workaround would be possible.您可能想阅读以下内容:
http://www.akkadia.org/drepper/tls.pdf< /a>
1) MSVC 不支持 C99。 GCC 确实和其他编译器尝试 GCC 兼容性。
编辑编译器对
__thread
支持的详细信息可在此处找到:http://chtekk.longitekk.com/index.php?/archives/2011/02/C8.html
2) 仅 C++ 支持初始化程序并且它必须是恒定的。
3)非多线程应用程序是单线程应用程序。
You probably want to read this:
http://www.akkadia.org/drepper/tls.pdf
1) MSVC doesn't support C99. GCC does and other compilers attempt GCC compatibility.
edit A breakdown of compiler support for
__thread
is available here:http://chtekk.longitekk.com/index.php?/archives/2011/02/C8.html
2) Only C++ supports an initializer and it must be constant.
3) Non-multi-threaded applications are single-threaded applications.