In Python: How to run code atomic with out interruption?

97 Views Asked by At

I saw already discussions about the synchronised question: How to prevent two threads entering the same section of code? They introduce some kind of synchronised decorator like in Java.

But that is not my problem. I would like to run a few lines of code at once. The Python interpreter shall not switch to another thread in between those lines of code. Maybe "without context switching" is the right description. Other threads shall wait until the python interpreter has completed the specified lines. And afterwards it can decide again to stop the execution of the current thread and excecute another thread for a while.

Is there a way to do that? Something like this:

with atomic_lock:
    do_stuff()
    # no context switch here - executed directly after another
    do_other_stuff()

What I would like to do:

I would like to loop through the keys in a dictionary. The for loop fails if the dictionary is changed while the loop is executing. For example if a key is added. That happens on many other places in my code. So my idea was to prevent any other code from executing while the for loop is executed. But maybe there is a different solution? Can I get a lock on that dictionary?

1

There are 1 best solutions below

0
EinEsellesEniE On

The simple answer is: That is not possibele yet. The only possible way is to work with locks, because that is the only suitable thing that is implemented in the python interpreter.