9

While reading about the function InterlockedIncrement I saw the remark that the variable passed must be aligned on a 32-bit boundary. Normally I have seen the code which uses the InterlockedIncrement like this:

class A
{
 public:
   A();
   void f();

 private:
  volatile long m_count;
};

A::A() : m_count(0)
{
}

void A::f()
{
  ::InterlockedIncrement(&m_count);
}

Does the above code work properly in multi-processor systems or should I take some more care for this?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
Naveen
  • 74,600
  • 47
  • 176
  • 233

4 Answers4

16

It depends on your compiler settings. However, by default, anything eight bytes and under will be aligned on a natural boundary. Thus an "int" we be aligned on a 32-bit boundary.

Also, the "#pragma pack" directive can be used to change alignment inside a compile unit.

I would like to add that the answer assumes Microsoft C/C++ compiler. Packing rules might differ from compiler to compiler. But in general, I would assume that most C/C++ compilers for Windows use the same packing defaults just to make working with Microsoft SDK headers a bit easier.

Torlack
  • 4,395
  • 1
  • 23
  • 24
0

The code looks fine (variables will be properly aligned unless you specifically do something to break that - usually involving casting or 'packed' structures).

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
0

Yes, this will work fine. Compilers usually do align unless instructed otherwise.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
0

Strictly speaking, it really depends on your usage of A - for instance, if you pack an "A" object within a shell ITEMIDLIST, or a struct with a bad "pragma pack" the data may not be properly aligned.

Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88