联锁功能 c++
我正在开发一个使用共享内存和互锁功能的系统。
假设我有易失性无符号整数n,a,b
。我想原子地执行以下伪代码:
if (a <= n && n < b)
{
n++;
}
else
{
//Do nothing
}
我该怎么做?您可以同时使用多个互锁功能吗?
I am developing a system that uses shared memory and interlocked functions.
Let's assume i have volatile unsigned int n, a, b
. I want to do the following pseudocode atomicly:
if (a <= n && n < b)
{
n++;
}
else
{
//Do nothing
}
How would I do that? Can you use multiple Interlocked functions together?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要一个锁或 CAS 类型的操作。再多的
易失性
在这里也无济于事。真正的原子数据类型也不会。You need a lock or a CAS type operation. No amount of
volatile
is going to help here. Neither will a true atomic data type.同步原语(例如信号量、互斥体等)由特定于操作系统的库提供,而不是由语言本身提供。 C/C++ 没有内在的“synchronized”关键字。
如果您在 Linux 上编程,请查看 Posix 线程或 Boost 库:
http://www. yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
如果您在本机 Windows Win32(Win98 或更高版本)上编程,则可以使用 EnterCriticalSection() 等 API和 InterlockedAdd() 等:
http:// /msdn.microsoft.com/en-us/library/ms686353%28v=VS.85%29.aspx
但是,如果您使用 .Net 对 Windows 进行编程,您又回到了作为标准 .Net 库一部分的同步原语:
http:// /msdn.microsoft.com/en-us/library/ms173179.aspx
'希望有帮助.. PSM
Synchronization primitives (such as semaphores, mutexes, etc.) are provided by OS-specific libraries, and not in the language itself. C/C++ have no intrinsic "synchronized" keyword.
If you're programming on Linux, look at Posix threads or the Boost library:
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
If you're programming on native Windows Win32 (Win98 or higher), you can use APIs like EnterCriticalSection() and InterlockedAdd(), among others:
http://msdn.microsoft.com/en-us/library/ms686353%28v=VS.85%29.aspx
If you're programming Windows with .Net, however, you're back to synchronization primitives being part of the standard .Net libraries:
http://msdn.microsoft.com/en-us/library/ms173179.aspx
'Hope that helps .. PSM