Thread safetyness in Python
Jeff Epler
jepler at unpythonic.net
Wed Jul 3 10:45:00 EDT 2002
On Wed, Jul 03, 2002 at 02:12:39PM +0000, Gerhard Haering wrote:
> John Goerzen wrote:
> > 1. In C, a++ would be atomic because CPUs have an atomic increment
> > operation, in most cases.
>
> What about SMP systems?
Being one instruction is not enough to be atomic in SMP systems. For
instance, quoting from "AMD x86-64 Architecture", Volume 1, page 90:
Lock Prefix. The LOCK prefix causes certain read-modify-write
instructions that access memory to occur atomically. The mechanism
for doing so is implementation-dependent (for example, the mechanism
may involve locking of data-cache lines that contain copies of the
referenced memory operands, and/or bus signaling or packet-messaging
on the bus). The prefix is intended to give the processor exclusive
use of shared memory operands in a multiprocessor system.
The prefix can only be used with forms of the following instructions
that write a memory operand: ADC, ADD, AND, BTC, BTR, BTS, CMPXCHG,
CMPXCH8B, DEC, INC, NEG, NOT, OR, SBB, XADD, XCHG, and XOR. An
invalid-opcode exception occurs if LOCK is used with any other
instruction.
(this is largely the same for plain 'ol x86, but that's from the manual
I have at hand)
This means that if two processors are executing 'INC' at about the same
time, the R-M-W steps could take place like
CPU0 CPU1
Read 0
Read 0
Modify Modify
Write 1
Write 1
Only 'LOCK INC' will ensure that the operation takes place in an atomic
fashion.
Of course, 'LOCK INC' is bad for performance, and a compiler won't
generate it for every increment instruction. Some standard has defined
"atomic_t" and "sigatomic_t" integral data types which have the desired
behavior. I don't know offhand if this is ISO C, POSIX, or something
else, though.
Jeff
More information about the Python-list
mailing list