I've worked with Python for a while, but I've never really done any concurrency in it before today. I stumbled upon this blog post and decided to make a similar (but simpler) example:
import os
import threading
import Queue
class Worker(threading.Thread):
def __init__(self, queue, num):
threading.Thread.__init__(self)
self.queue = queue
self.num = num
def run(self):
while True:
text = self.queue.get()
#print "{} :: {}".format(self.num, text)
print "%s :: %s" % (self.num, text)
self.queue.task_done()
nonsense = ["BLUBTOR", "more nonsense", "cookies taste good", "what is?!"]
queue = Queue.Queue()
for i in xrange(4):
# Give the worker the queue and also its "number"
t = Worker(queue, i)
t.setDaemon(True)
t.start()
for gibberish in nonsense:
queue.put(gibberish)
queue.join()
It seems to work fine, but there seems to be some problem with the prints which I cannot figure out. A couple of test runs:
chris@DPC3:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
1 :: more nonsense
3 :: cookies taste good
2 :: what is?!
chris@DPC3:~/code/pythonthreading$ python owntest.py
0 :: BLUBTOR
2 :: more nonsense
3 :: cookies taste good0 :: what is?!
chris@DPC3:~/code/pythonthreading$ python owntest.py
2 :: BLUBTOR
3 :: more nonsense1 :: cookies taste good
2 :: what is?!
chris@DPC3:~/code/pythonthreading$
Why is the output formatted this oddly?