简体   繁体   English

Static 多线程中的成员变量

[英]Static member variables in multithreading

As all of you know, despite how many objects instantiated, only one instance of static member variables are stored in the BSS segment.众所周知,尽管实例化了多少对象,但只有一个 static 成员变量实例存储在 BSS 段中。 Accordingly, consider having some thread which instantiates a class with a static member variable and changes static member frequently;因此,考虑有一些线程用 static 成员变量实例化 class 并经常更改 static 成员; my question is whether the static member is thread-safe or not.我的问题是 static 成员是否是线程安全的。

Variables do not know anything about threads.变量对线程一无所知。 Class static member variables are not inherently thread-safe. Class static 成员变量本质上不是线程安全的。 You might consider putting them in thread-local storage, or making sure the members' data structures are themselves thread-safe.您可以考虑将它们放在线程本地存储中,或者确保成员的数据结构本身是线程安全的。

You also mentioned "static member functions" but those are immaterial to this question: it doesn't matter how you modify your static member variables, doing so is not inherently thread-safe, whether modified via static member functions, regular member functions, or non-member functions.您还提到了“静态成员函数”,但这些对这个问题无关紧要:您如何修改 static 成员变量并不重要,这样做本质上不是线程安全的,无论是通过 static 成员函数、常规成员函数还是非成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM