#!/usr/bin/env python

from random import randint              # random integer function
from time import time, ctime, sleep     # import time stuff
from Queue import Queue                 # threaded Queue structure
from myThread import MyThread           # import MyThread class

# produce item for queue
def writeQ(queue):
    print 'producing object for Q...',
    queue.put('xxx', 1)
    print "size now", queue.qsize()

# consume item for queue
def readQ(queue):
    val = queue.get(1)
    print 'consumed object from Q... size now', queue.qsize()

# producer loop
def writer(queue, loops):
    for i in range(loops):
        writeQ(queue)
        sleep(randint(1, 3))

# consumer loop
def reader(queue, loops):
    for i in range(loops):
        readQ(queue)
        sleep(randint(2, 5))

def main():
    funcs = [ writer, reader ]          # function list
    nfuncs = range(len(funcs))          # number of functions
    nloops = randint(2, 5)              # random iterations
    q = Queue(32)                       # queue size

    # create threads
    threads = []
    for i in nfuncs:
        t = MyThread(funcs[i], (q, nloops), funcs[i].__name__)
        threads.append(t)

    # start threads
    for i in nfuncs:
        threads[i].start()

    # wait for threads to complete
    for i in nfuncs:
        threads[i].join()

    print 'all DONE'

if __name__ == '__main__':
    main()

