On the Intel type of X86 processors including AMD, increasingly there are more CPU cores or processors running in parallel.
In the old days when there was a single processor, the operation:
++ I;
Wocould be thread safe because it was one machine instruction on a single processor. These days laptops have numerous CPU Cores so that even single instruction operations aren't safe. What do you do? Do you need to wrap all operations in a mutex or semaphore? Well, maybe you don't need too.
Fortunately, the x86 has an instruction prefix that allows a few memory referencing instruction to execute on specific memory locations exclusively.
There are a few basic structures that can use this:
(For the GNU Compiler)
Void atom_inc (volatile int * num)
{
_ ASM _ volatile _ ("lock incl % 0": "= m" (* num ));
}
Void atom_dec (volatile int * num)
{
_ ASM _ volatile _ ("lock Decl % 0": "= m" (* num ));
}
Int atom_xchg (volatile int * m, int inval)
{
Register int val = inval;
_ ASM _ volatile _ ("lock xchg % 1, % 0": "= m" (* m), "= r" (VAL ): "1" (inval ));
Return val;
}
Void atom_add (volatile int * m, int inval)
{
Register int val = inval;
_ ASM _ volatile _ ("lock add % 1, % 0": "= m" (* m), "= r" (VAL ): "1" (inval ));
}
Void atom_sub (volatile int * m, int inval)
{
Register int val = inval;
_ ASM _ volatile _ ("lock sub % 1, % 0": "= m" (* m), "= r" (VAL ): "1" (inval ));
}
?
For the Microsoft Compiler:
?
Void atom_inc (volatile int * num)
{
_ ASM
{
MoV ESI, num
Lock Inc dword ptr [esi]
};
}
Void atom_dec (volatile int * num)
{
_ ASM
{Mov ESI, num
Lock dec dword ptr [esi]
};
}
Int atom_xchg (volatile int * m, int inval)
{
_ ASM
{
MoV eax, inval
MoV ESI, m
Lock xchg eax, dword ptr [esi]
MoV inval, eax
}
Return inval;
}
Void atom_add (volatile int * num, int Val)
{
_ ASM
{Mov ESI, num
MoV eax, Val
Lock add dword ptr [esi], eax
};
}
Void atom_sub (volatile int * num, int Val)
{
_ ASM
{Mov ESI, num
MoV eax, Val
Lock sub dword ptr [esi], eax
};
}
?
The lock prefix is not universally applied. it only works if all accesses to the locations also use lock. so, even though you use "Lock" in one section of code, another section of code that just sets the value will not be locked out. think of it as just a mutex.
Basic usage:
?
Class poll
{
Int m_pollcount;
....
....
?
Void polladd ()
{
Atom_inc (& m_pollcount );
}
};
The above example increments a poll object count by one.
Src = http://www.mohawksoft.org /? Q = node/78
Atomic operations on the x86 Processors