在C99使用__thread [英] Using __thread in c99
问题描述
我想定义几个变量作为线程特定使用__thread存储类。但三个问题让我犹豫了:
- 难道是真的C99标准?或者更重要的是,如何好是编译器支持?
- 请问变量,每个线程被初始化?
- 请非多线程程序把它们当作纯老全局?
要回答您的具体问题:
- 不,这不是C99的一部分。你不会找到它在n1256.pdf提及任何地方(C99 + TC1 / 2/3),还是原来的C99标准。
- 是
__线程
变量开始了在每一个新线程的初始值。 - 从程序行为的角度来看,线程本地存储类变量的行为pretty大致相同的非多线程程序平原全局。但是,它们产生多位运行成本(存储器和启动时间),并且可以有与尺寸和线程局部变量的数目的限制的问题。所有这一切都比较复杂,取决于你的程序是static-或动态链接和变量是否驻留在主程序或共享库...
实现C / POSIX(例如错误号
等)外,线程本地存储类,其实并不是非常有用,在我看来。它是pretty多用于避免干净地围绕必要的状态传递一个上下文指针或类似的形式的拐杖。你可能会认为这可能是让周围破接口,如的qsort
不采取上下文指针有用的,但遗憾的是没有保证的qsort
将调用那个叫的qsort
同一个线程比较函数。它可能向下突破的工作,并在多个线程中运行它。同样适用于大多数其他接口,其中这种解决办法将是可能的。
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?
To answer your specific questions:
- No, it is not part of C99. You will not find it mentioned anywhere in the n1256.pdf (C99+TC1/2/3) or the original C99 standard.
- Yes,
__thread
variables start out with their initialized value in every new thread. - From a standpoint of program behavior, thread-local storage class variables behave pretty much the same as plain globals in non-multi-threaded programs. However, they do incur a bit more runtime cost (memory and startup time), and there can be issues with limits on the size and number of thread-local variables. All this is rather complicated and varies depending on whether your program is static- or dynamic-linked and whether the variables reside in the main program or a shared library...
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 like qsort
that don't take a context pointer, but unfortunately there is no guarantee that qsort
will call the comparison function in the same thread that called qsort
. 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.
这篇关于在C99使用__thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!