多线程静态变量
我有一个多线程C代码,我想让一个全局变量成为线程私有的。也就是说,每个线程都有它自己的副本......这样做的最佳方法是什么?
I have a multithreaded C code, I want to make a global variable to be thread-private. That is each thread has it's own copy of it...what is the best way of doing so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要的称为 TLS。 TLS 的声明方式与任何其他全局(静态)变量一样,但语法取决于实现。例如:
Boost和TBB都有自己的可移植TLS,但它是C++,而不是C。
What you want is called TLS. TLS is declared just like any other global (static) variable, but syntax is implementation dependent. For example:
Boost and TBB have their own portable TLS, but it is C++, not C.
对于 Windows NT 引擎,可以在线程启动时将指针传递给线程。这个指针可以指向任何可以指向的东西:在你的例子中是一个变量。
就我个人而言,我更喜欢让它指向索引结构的成员,其中每个成员都属于特定线程,并包含与线程相关的信息,例如句柄、处理统计信息等。
如果您选择此路线,请记住索引结构的每个成员其大小应等于处理器缓存行大小的偶数倍(x86 上为 32 或 64 字节),否则线程在访问各自的结构时将开始在缓存中相互冲突。索引结构也应该从缓存行大小的偶数倍开始。
For the Windows NT engine it is possible to pass a pointer to a thread when it is being started. This pointer can point to anything that can be pointed to: in your case a variable.
Personally I prefer to let it point to a member of an indexed structure where every member belongs to a specific thread and contains information pertaining to the thread such as handle, processing statistics etc.
If you go this route remember that each member of the indexed structure should have a size equal to an even multiple of the processor's cache line size (32 or 64 bytes on x86), otherwise the threads will start colliding with each other in the cache when accessing their respective structures. The indexed structure should also begin on an even multiple of the cache line size.
您正在描述局部变量,而不是全局变量。
通过使用 C 习惯用法将变量设置为实例变量(例如将参数传递给线程),可以轻松地安排它。
You are describing local variables, not global variables.
It is easily arranged by making the variable an instanced variable using
C
idioms, such as passing a parameter to the thread.