Are range iterators thread safe?

S

Stefan Behnel

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

Stefan
 
S

Stefan Behnel

Ben Finney, 20.10.2011 13:23:
The GIL applies only to CPython.

and PyPy.

What is the answer for other Python
implementations which don't have a GIL?

That would basically be Jython and IronPython.

Note that none of the three alternative implementations currently supports
Python language version 3. So, the current answer for all existing Python 3
implementations is: the GIL ensures that it's thread safe.

Stefan
 
I

Ian Kelly

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top