# Q-12 MCS 275 Thu 20 Apr 2017 : quiz12b.py
"""
We want to simulate the number of invitees to a party with threds.
Each invitee has a probability p of showing up or not.
If the function random() of the module random returns a number less than p,
then the invitee is present, otherwise the invitee is absent.
Define a class Invitee, inheriting from the Thread class.
Every invitee has a unique name: the string representation
of an integer number.
The response to the invitation is stored in a shared list.
"""
from threading import Thread
from random import random

class Invitee(Thread):
    """
    Simulates being present or absent.
    """
    def __init__(self, name, bias, tally):
        """
        The name of the thread is the string representation
        of an integer number.  The bias of the visitor is a float
        in the interval [0, 1], with the probability that the
        visitor will be present.  The tally is a list, shared between
        all threads, initialized to False.
        """
        Thread.__init__(self, name=name)
        self.present = tally
        self.probability = bias

    def run(self):
        """
        The visitor is present or absent.
        """
        idx = int(self.getName())
        visit = random()
        self.present[idx] = (visit < self.probability)

def main():
    """
    Prompts the user for a number of invitees.
    Starts the voting process.
    """
    nbr = int(input('Give the number of voters : '))
    response = [False for _ in range(nbr)]
    invitees = [Invitee(str(k), random(), response) for k in range(nbr)]
    for invitee in invitees:
        invitee.start()
    for invitee in invitees:
        invitee.join()
    print('Response :', response, 'sum =', sum(response))

main()
