Multi-threaded Zundokokiyoshi using Event and Queue

I wanted to check the multi-thread operation, so I made Zundokokiyoshi. Ask three singers to thread and sing "Zun" or "Doko" at 1-second intervals. Queue is multi-thread compatible and can retrieve stored data from multiple threads in order. This is likened to a microphone. I'm comparing ZUN or DOKO using ʻisinstead of==` because different threads should refer to the same object.

# -*- coding:utf-8 -*-

import time
from random import random
from threading import Thread, Event
from Queue import Queue

ZUN = "Dung"
DOKO = "Doco"
KIYOSHI = "Ki yo shi!"

class Singer(Thread):

    def __init__(self, mic):
        '''Preparation:Hold the microphone and wait for start and end instructions'''
        super(Singer, self).__init__()
        self.mic = mic
        self.singing = Event()

    def run(self):
        '''start:Sing Zun or Doko every second'''
        self.singing.set()
        while self.singing.is_set():
            time.sleep(1)
            word = ZUN if random() < 0.5 else DOKO
            self.mic.put(word)

    def stop(self):
        '''End:Finish singing'''
        if self.singing.is_set():
            self.singing.clear()
            self.join()

def zundoko():

    #Microphone
    mic = Queue()

    #Have three singers start singing into one microphone
    the_number_of_singer = 3
    singers = [Singer(mic) for i in range(the_number_of_singer)]
    for singer in singers:
        singer.start()

    try:
        #If you hear "Doko" after "Zun" continues 4 times, shout "Ki Yo Shi!"
        zun = 0
        kiyoshi = False
        while kiyoshi == False:
            word = mic.get()
            print word
            if word is ZUN:
                zun += 1
            elif word is DOKO:
                if zun >= 4:
                    kiyoshi = True
                zun = 0
        print KIYOSHI
    finally:
        #Have the singer finish singing(CTRL+Even when forced to terminate with C)
        for singer in singers:
            singer.stop()

if __name__ == '__main__':
    zundoko()

Recommended Posts

Multi-threaded Zundokokiyoshi using Event and Queue
Stack and Queue in Python
When using if and when using while
This and that using reflect
Try using pytest-Overview and Samples-