Skip to content

Instantly share code, notes, and snippets.

@CUXIDUMDUM
Created May 24, 2015 18:55
Show Gist options
  • Save CUXIDUMDUM/bbe14bbaa7bbcd66d4d6 to your computer and use it in GitHub Desktop.
Save CUXIDUMDUM/bbe14bbaa7bbcd66d4d6 to your computer and use it in GitHub Desktop.
threads2
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