Created
October 24, 2016 14:41
-
-
Save anonymous/6a0c57d734a6b1c3097d10dd253ae012 to your computer and use it in GitHub Desktop.
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
import time, queue | |
from threading import Thread | |
class threadedGenerator(): | |
def function_wrapper(self, q, sentinel, fun, **kwargs): | |
for i in fun(**kwargs): | |
q.put(i) | |
q.put(sentinel) | |
def gen(self, fun, sentinel=None, **kwargs): | |
q = queue.Queue() | |
t = Thread(target=self.function_wrapper, args=[q, sentinel, fun], kwargs=kwargs).start() | |
for i in iter(q.get, sentinel): | |
yield(i) | |
###### use the gen method from threadedGenerator as a wrapper for a | |
###### generator function (in this case fillstack()) to let it run on | |
###### a separate thread. The current script thus prints a counter | |
###### with steady 1 sec intervalls, despite the 5 second sleep in the | |
###### generator function | |
def fillstack(name): | |
for i in [x for x in range(1,11)]: | |
yield i | |
if i == 5: time.sleep(5) | |
if __name__ == '__main__': | |
tg = threadedGenerator() | |
for i in tg.gen(fillstack, name='test'): | |
print(i) | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment