how to use two threads to produce even and odd numbers?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jun 14 22:18:37 EDT 2013


On Fri, 14 Jun 2013 04:50:05 -0700, Zoe Wendy wrote:

> I am going to compile a small python program in order to use Queue to
> produce a random with a thread. For example,  using one thread to print
> odd number, while another thread to print even number.
> 
> Here is my codes, please offer me some advice:

Unfortunately your code has been mangled by your mail program. Please 
turn off so-called "Rich Text", or HTML mail, since that causes the 
formatting of the code to be mangled. I will try to reconstruct the 
formatting, but if I get it wrong, don't blame me :-)

I have also fixed a couple of syntax errors, which are shown with 
comments below.


# === your code -- reconstructed ===
import threading
import random
import time
from Queue import Queue
 
class jishu (threading.Thread):
    def __init__(self, threadname, queue):
        threading.Thread.__init__(self, name = threadname)
        self.sharedata = queue
    def run(self):
        # for i %2 == 1 in range(200):  *** THIS LINE IS WRONG ***
        for i in range(1, 200, 2):
            print self.getName(), 'adding', i, 'to queue'
            self.sharedata.put(i)
            time.sleep(random.randrange(10)/10.0)
        print self.getName(),'Finished'

class oushu(threading.Thread):
    def __init__(self, threadname, queue):
        threading.Thread.__init__(self, name = threadname)
        self.sharedata = queue
    def run(self):
        # for i %2 == 0 in range(200):  *** THIS LINE IS WRONG ***
        for i in range(0, 200, 2):
            print self.getName(), 'got a value:', self.sharedata.get()
            time.sleep(random.randrange(10)/10.0)
        print self.getName(),'Finished'

# === end code ===


You have one thread, jishu, that feeds *odd* numbers into a queue, and 
another thread, oushu, that takes them out. Neither thread actually gets 
run though: you create the classes, but you don't start the threads 
running.

Add this to the end of the code:


data = Queue()
a = jishu('jishu', data)
b = oushu('oushu', data)
a.start()
time.sleep(2)
b.start()


and then run the program, and you will see output like this, only much 
more of it:




jishu adding 1 to queue
jishu adding 3 to queue
jishu adding 5 to queue
jishu adding 7 to queue
[...]
oushu got a value: 1
jishu adding 61 to queue
jishu adding 63 to queue
oushu got a value: 3
jishu adding 65 to queue
oushu got a value: 5
oushu got a value: 7
[...]
oushu got a value: 183
jishu adding 199 to queue
jishu Finished
oushu got a value: 185
oushu got a value: 187
oushu got a value: 189
oushu got a value: 191
oushu got a value: 193
oushu got a value: 195
oushu got a value: 197
oushu got a value: 199
oushu Finished



Or something similar to that.


Does this help?


-- 
Steven



More information about the Python-list mailing list