多线程静态变量

发布于 2024-11-02 15:54:54 字数 70 浏览 1 评论 0原文

我有一个多线程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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

素手挽清风 2024-11-09 15:54:54

您想要的称为 TLS。 TLS 的声明方式与任何其他全局(静态)变量一样,但语法取决于实现。例如:

// Visual C/C++ and Intel C/C++ on Windows
__declspec(thread) int number;

// GCC and Intel C/C++ on Linux
__thread int number;

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:

// Visual C/C++ and Intel C/C++ on Windows
__declspec(thread) int number;

// GCC and Intel C/C++ on Linux
__thread int number;

Boost and TBB have their own portable TLS, but it is C++, not C.

听,心雨的声音 2024-11-09 15:54:54

对于 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.

酒废 2024-11-09 15:54:54

您正在描述局部变量,而不是全局变量。

通过使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文