在线程中设置全局变量
我需要一个字符串作为全局变量。多个线程可以设置全局变量。我应该为此使用互斥体吗?或者操作系统会处理此类操作吗? 使用互斥锁会影响应用程序性能。
我不关心行动发生的顺序。我担心数据损坏。 有人可以让我知道这件事吗?
I need to have a string as a global variable. There is a possibility for multiple threads to set the global variable. Should I have to go for mutex for this? Or will OS handle such actions.
Going for mutex affects the application performance.
I am not concerned about the order of actions happening. I am afraid of the data corruption.
Could somebody let me know about this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您理解所有的担忧。如果全局变量可能被损坏,您肯定需要将其锁定在互斥体中。这将影响性能,因为根据定义,这部分现在将是同步的。话虽这么说,您将需要根据需要锁定代码的最小部分,以最大限度地减少调用同步代码的时间。
It sounds like you understand all of the concerns. If the global variable can be corrupt you definitely need to lock it in a mutex. This will affect performance, since this part is by definition now going to be synchronous. That being said, you will want to lock the smallest part of the code as necessary, to minimize the time that synchronous code is being called.
你的全局变量是什么?指向字符串缓冲区的指针,还是缓冲区本身?
在许多体系结构(包括 AFAIR 32 位 x86)上,覆盖单个指针是原子的。
这个例子可能有效:
What's your global variable? A pointer to the string buffer, or the buffer itself?
On many architectures (including AFAIR 32-bit x86) overwriting a single pointer is atomic.
This example might work:
为此,您可以使用线程本地存储。
不幸的是,当前的 C99 标准中没有指定它,但 C1X 中可能会有。现在,您可以使用特定于编译器的实现(GCC、ICC 和 Visual C 都有)。
You can use Thread-Local Storage for this.
Unfortunately, its not specified in current C99 standart, but possible will be there in C1X. For now, you can use compiler-specific implementations (GCC, ICC and Visual C have it).
就标准而言,是的,您必须使用互斥体。如果不这样做会导致未定义的行为。实际上,大多数机器架构都没有问题。 C 标准 (C1x) 的未来版本将具有原子类型,如果在这里使用,肯定会在没有锁的情况下使分配变得安全(尽管可能在缺乏真正原子的破碎拱上使用内部锁)。
As far as the standards are concerned, yes, you must use a mutex. Failure to do so results in undefined behavior. In practice, most machine architectures will have no problem with this. Future versions of the C standard (C1x) will have atomic types which, if used here, would definitely make the assignment without lock safe (albeit possibly using an internal lock, on broken archs that lack real atomics).