Look free ID genertion (was: Is there a more efficient threading lock?)

Chris Angelico rosuav at gmail.com
Wed Mar 1 14:41:46 EST 2023


On Thu, 2 Mar 2023 at 06:37, <avi.e.gross at gmail.com> wrote:
>
> If a workaround like itertools.count.__next__() is used because it will not
> be interrupted as it is implemented in C, then I have to ask if it would
> make sense for Python to supply something similar in the standard library
> for the sole purpose of a use in locks.

That's not lock-free :) The only way that it works is because it's
locked against other threads doing the same job. Lock-free ID
generation means that:

1) Two threads can request IDs simultaneously and will not block each other
2) No two "request an ID" calls will ever return the same value
3) Preferably (but not required), IDs are not wasted.

PostgreSQL has ways of doing this, and there are a few other ways, but
simply using a count object and relying on the GIL isn't going to
achieve the first (though it'll happily achieve the other two).

ChrisA


More information about the Python-list mailing list