开发者

Interlocked functions c++

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 &&开发者_运维技巧amp; n < b)
{
    n++;
}
else
{
    //Do nothing
}

How would I do that? Can you use multiple Interlocked functions together?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜