Is there a way to protect a piece of critical code?
no-spam at no-spam-no-spam.invalid
Wed Jan 10 14:25:34 CET 2007
Hendrik van Rooyen wrote:
> I would like to do the following as one atomic operation:
> 1) Append an item to a list
> 2) Set a Boolean indicator
I doubt you have to worry at all about this in such simple single-single queue - if there is not a much more complex condition upon the insert order.
And what should the indicator tell? that a new element is there?
The list itself tells its the length, its guaranteed to be increased _after_ .append()
And you can .pop(0) just so - catching/retring at Key/IndexError at least.
List .append() and .pop() will be atomic in any Python though its not mentioned explicitely - otherwise it would be time to leave Python.
There is also Queue.Queue - though it has unneccessary overhead for most purposes.
A function to block Python interpreter thread switching in such VHL language would be nice for reducing the need for spreading locks in some cases (huge code - little critical sections). Yet your example is by far not a trigger for this. I also requested that once. Implementation in non-C-Pythons may be difficult.
Generally there is also technique for optimistic unprotected execution of critical sections - basically using an atomic counter and you need to provide code for unrolling half executions. Search Google.
> It would be almost like getting and holding the GIL,
> to prevent a thread swap out between the two operations.
> - sort of the inverted function than for which the GIL
> seems to be used, which looks like "let go", get control
> back via return from blocking I/O, and then "re - acquire"
> Is this "reversed" usage possible?
> Is there some way to prevent thread swapping?
> The question arises in the context of a multi threaded
> environment where the list is used as a single producer,
> single consumer queue - I can solve my problem in various
> ways, of which this is one, and I am curious as to if it is
> possible to prevent a thread swap from inside the thread.
> - Hendrik
More information about the Python-list