Last active
August 29, 2015 14:08
-
-
Save wenhoujx/0cdda6bb36442e068392 to your computer and use it in GitHub Desktop.
how to trigger a generator thread safety error.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
generator are not thread safe, two or more thread accessing the same generator | |
causes an error: | |
ValueError: generator already executing | |
example comes from: | |
http://stackoverflow.com/questions/20043472/python-multithreading-why-generators-are-not-thread-safe-what-happens-when-it | |
""" | |
import threading | |
class CountThread(threading.Thread): | |
def __init__(self, gen): | |
super(CountThread, self).__init__() | |
self.gen = gen | |
self.number_seen = 0 | |
def run(self): | |
# does nothing but counting | |
for i in self.gen: | |
self.number_seen += 1 | |
# shortcut generator expression, or you can write with yeild | |
igen = (i for i in xrange(10000)) | |
t = [CountThread(igen), CountThread(igen)] | |
[tt.start() for tt in t] | |
[tt.join() for tt in t] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment