Created
May 24, 2015 18:55
-
-
Save CUXIDUMDUM/bbe14bbaa7bbcd66d4d6 to your computer and use it in GitHub Desktop.
threads2
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 logging | |
from multiprocessing.dummy import Pool | |
import threading | |
import random | |
import time | |
import Queue | |
class Foo(object): | |
def __init__(self): | |
self.logger = logging.getLogger("Foo") | |
def play(self, winningno): | |
self.logger.info("Playing with %s" % winningno) | |
rint = random.randint(20, 100) | |
notdivisible = bool(rint % winningno) | |
c = threading.current_thread() | |
if not c.name.startswith("Some"): | |
c.name = "Somethread%s" % winningno | |
time.sleep(1) | |
if notdivisible: | |
self.logger.info("Got %s, playing again" % rint) | |
return self.play(winningno) | |
else: | |
self.logger.info("Got %s, playing with %s, %s am out" % (rint, winningno, threading.current_thread().n\ | |
ame)) | |
return "done" | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
formatter = logging.Formatter("%(process)s - %(threadName)s - %(message)s") | |
ch = logging.StreamHandler() | |
ch.setLevel(logging.DEBUG) | |
ch.setFormatter(formatter) | |
logger.addHandler(ch) | |
def worker(input): | |
obj, params, q = input | |
func = getattr(obj, 'play') | |
while True: | |
l = func(params) | |
if l == "done": | |
q.put("done-%s" % params) | |
return #this is required else prog never completes | |
threads = [] | |
a = Foo() | |
q = Queue.Queue() | |
for i in xrange(1, 19): | |
t = threading.Thread(target=worker, args=((a, i, q),), name="Something%s" % i) | |
threads.append(t) | |
t.setDaemon = True | |
t.start() | |
# total = len(threads) | |
# while True: | |
# data = q.get(1) | |
# total = total - 1 | |
# logger.info("Got %s, %s remaining" % (data, total)) | |
# if not total: | |
# break | |
# time.sleep(1) | |
#only when not daemon | |
# for t in threads: | |
# t.join() | |
# pool = Pool(5) | |
# a = Foo() | |
# # while True: | |
# # r = a.play(2) | |
# # l = r.next() | |
# # if l == "done": | |
# # break | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment