Hello Friends,

I am trying to porting an unix c++ program into windows using MSVC8.0 compiler. In my unix version there are some lines like

#include <sys/atomic.h>
...
atomic_add_int_nv()
...

Now, pls help me to find out the Win version of these code segments.

Thanks,
Amit

Dani AI

Generated

Short answer: the Unix atomic_add_int_nv() semantic (atomic add, return the new value) maps cleanly to either C++11 atomics or the Win32 Interlocked family. As suggested, first confirm the exact semantics in your source: if the call returns the new value (the “_nv” suffix), you must preserve that behavior on Windows. ’s ATOMIC.H is a useful reference implementation; pointed toward the Win interlocked APIs for Windows.

If you can use a modern compiler, prefer C++ atomics for portability and clarity:

#include <atomic>

std::atomic<int> counter{0};
int delta = 3;
int newVal = counter.fetch_add(delta) + delta; // fetch_add returns old value; add delta to get new value

Reference: std::atomic - cppreference

If you must stay on MSVC8 (Visual Studio 2005) or otherwise lack C++11 atomics, use the Win32 Interlocked calls. On Win32 the typical mapping is to InterlockedExchangeAdd, which returns the previous value, so add the delta to get the new value:

#include <windows.h>

LONG newVal = InterlockedExchangeAdd(&myLong, delta) + delta;

Reference: Interlocked Variable Access - Microsoft Docs

A small compatibility wrapper you can drop into legacy code:

inline LONG atomic_add_int_nv(LONG volatile *addr, LONG delta)
{
    return InterlockedExchangeAdd(addr, delta) + delta;
}

Notes and cautions: use the 64-bit variants on 64-bit counters (InterlockedExchangeAdd64), match the integer size and alignment, and remember Interlocked functions imply full memory barriers. If upgrading the compiler is possible, migrating to std::atomic gives clearer semantics and portable memory-order control.

Recommended Answers

All 3 Replies

A starting point for you would be to specify what atomic_add_int_nv() actually does under unix. Forum readers are not mind-readers, and not generally all that good at working out what arbitrarily named non-standard functions do.

If you look up the documentation for atomic_add_int_nv(), you may also be able to work out the answer for yourself.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.