Are range iterators thread safe?

Ian Kelly ian.g.kelly at gmail.com
Thu Oct 20 12:00:57 EDT 2011


On Thu, Oct 20, 2011 at 3:22 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Steven D'Aprano, 20.10.2011 10:04:
>>
>> Using Python 3, are range_iterator objects thread-safe?
>>
>> I have tried this, and it seems to be safe:
>>
>> >>> from threading import Thread
>> >>> x = iter(range(4))
>> >>> def doit(x):
>> ...     print("result =", next(x))
>> ...
>> >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)]
>> >>> for t in threads:
>> ...     t.start()
>> ...
>> result = 0
>> result = 1
>> result = 2
>> result = 3
>
> The GIL ensures it's thread safe.

Because range_iterator objects are implemented in C and so calling the
__next__ method is only a single bytecode instruction, correct?  If
they were implemented in Python the GIL would make no such assurance.



More information about the Python-list mailing list