### Thread: How to use two threads to produce even and odd numbers?

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Posts
1
Rep Power
0

#### How to use two threads to produce even and odd numbers?

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.

import random
import time
from Queue import Queue

self.sharedata = queue

def run(self):
for i %2 == 1 in range(200):
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'

self.sharedata = queue

def run(self):

for i %2 == 0 in range(200):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
2. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Jun 2013
Posts
1
Rep Power
0
Take a look at this:

Code:
```import threading
from math import ceil
from random import random
from queue import Queue

def __init__(self, name, size, objQueue):
self.size = size
self.objQueue = objQueue

def run(self):
count = 0
while(count < self.size):
oddNumber = ceil((random() * 100))
if(oddNumber % 2 != 0):
print("Print Odd: " + str(oddNumber))
self.objQueue.put("Odd: " + str(oddNumber))
count += 1

def __init__(self, name, size, objQueue):
self.size = size
self.objQueue = objQueue

def run(self):
count = 0
while(count < self.size):
EvenNumber = ceil((random() * 100))
if(EvenNumber % 2 == 0):
print("Print Even: " + str(EvenNumber))
self.objQueue.put("Even: " + str(EvenNumber))
count += 1

objQueue = Queue(20)

odd.start()
even.start()

while not objQueue.empty():
print(objQueue.get())

if __name__ == "__main__":
Originally Posted by Yongsmith
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.

import random
import time
from Queue import Queue

self.sharedata = queue

def run(self):
for i %2 == 1 in range(200):
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'