Is there a way to protect a piece of critical code?

Hendrik van Rooyen mail at microcorp.co.za
Thu Jan 11 00:39:27 EST 2007


"robert" <no-spam at no-spam-no-spam.invalid> wrote:

> Hendrik van Rooyen wrote:
> > Hi,
> >
> > 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?

Yes -that is what I was using it for, and I got bitten - It would fail after
five or so hours
of running quite happily, because the consumer section, that tested the bool,
would try to pop from an empty queue - the consumer section also cleared the
boolean when the queue length was zero...

A classic case of fuzzy thinking...

>
> 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.

I changed to testing the length of the queue to solve the problem,
like I said I was just curious to see if the code could be protected.

>
> 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.
>
>
am aware of Queue module - the same app uses it for something else.
I dont like too many try -- excepts in the code - I find they confuse
me when I try to read it later - and in this case I cannot block on waiting for
the queue to fill.

> 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.
>
>
probably true - but even here - the problem would be solved by blocking
thread switching in the one thread, whereas using locks (or blocks as I would
tend to call them) requires fiddling in both threads.

> 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.
>
>
ok thanks will do

- Hendrik




More information about the Python-list mailing list