Using __thread in c99

前提是你 提交于 2019-12-10 17:18:26

问题


I would like to define a few variables as thread-specific using the __thread storage class. But three questions make me hesitate:

  1. Is it really standard in c99? Or more to the point, how good is the compiler support?
  2. Will the variables be initialised in every thread?
  3. Do non-multi threaded programs treat them as plain-old-globals?

回答1:


To answer your specific questions:

  1. 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.
  2. Yes, __thread variables start out with their initialized value in every new thread.
  3. 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.




回答2:


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.



来源:https://stackoverflow.com/questions/6869391/using-thread-in-c99

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!