correct way to catch exception with Python 'with' statement

Grant Edwards grant.b.edwards at gmail.com
Fri Dec 2 10:22:35 EST 2016


On 2016-12-02, Steve D'Aprano <steve+python at pearwood.info> wrote:

> I'm not an expert on the low-level hardware details, so I welcome
> correction, but I think that you can probably expect that the OS can
> interrupt code execution between any two CPU instructions.

Yep, mostly.  Some CPUs have "lock" features that allow two or more
adjacent instructions to be atomic.  Such a "lock" feature is usually
used to implement atomic read-modify write operations (e.g. increment
a memory byte/word, set/clear a bit in a memory byte/word) on CPUs
that don't have any read-modify-write instructions.  In general CISC
processors like x86, AMD64, 68K have read-modify-write instructions
that allow you to increment a memory location or set/clear a bit in
memory with a single instruction:

    INC.W  [R0]    # increment memory word whose addr is in register R0

Many RISC CPUs don't (many ARMs) and require three instructions to
increment a word in memory:

    LD  R1,[R0]    # read into register R1 memory word whose addr is in R0
    INC R1         # increment value in R1
    ST  R1,[R0]    # store from regster R1 into memory at addr in R0

Some such RISC CPUs have a mechism (other than the normal interrupt
enable/disable mechanism) to allow you to lock the CPU for the
duration of those three instructions to ensure that they are atomic.

-- 
Grant Edwards               grant.b.edwards        Yow! I request a weekend in
                                  at               Havana with Phil Silvers!
                              gmail.com            




More information about the Python-list mailing list