在C99使用__thread [英] Using __thread in c99

查看:136
本文介绍了在C99使用__thread的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义几个变量作为线程特定使用__thread存储类。但三个问题让我犹豫了:


  1. 难道是真的C99标准?或者更重要的是,如何好是编译器支持?

  2. 请问变量,每个线程被初始化?

  3. 请非多线程程序把它们当作纯老全局?


解决方案

要回答您的具体问题:


  1. 不,这不是C99的一部分。你不会找到它在n1256.pdf提及任何地方(C99 + TC1 / 2/3),还是原来的C99标准。

  2. __线程变量开始了在每一个新线程的初始值。

  3. 从程序行为的角度来看,线程本地存储类变量的行为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:

  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?

解决方案

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.

这篇关于在C99使用__thread的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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