I'm reading this question which asks if generators are thread-safe, and one answer said:
It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.
Another answer shows that you can use a lock to ensure that only one thread uses the generator at a time.
I'm new to multithreading. Can anyone devise an example to show what exactly happens when you use the generator without lock?
For example, it doesn't seem to have any problems if I do this:
import threading
def generator():
for i in data:
yield i
class CountThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
for i in gen():
print '{0} {1}'.format(self.name, i)
data = [i for i in xrange(100)]
gen = generator()
a = CountThread('a')
b = CountThread('b')
a.start()
b.start()