Python Thread Sum

python day 31

There are so many Reality Idol Shows this summer, since the fans are voting for the trainees, we will write a python program using Thread Module to calculate the votes fast. 

Key Concept

  •  _Lock: In order to add the number correctly, we will Lock the previous number then release

                                                       $$ total.call= self.call +vote $$

from time import sleep
from threading import Thread, Lock

class Idolaccount(object):
    
    def __init__(self):
        self._call=0
        self._lock=Lock()
        
    def addoil(self, vote):
        self._lock.acquire()
        try:
            total_call= self._call+ vote
            sleep(0.01)
            self._call= total_call
        finally:
            self._lock.release()
    
    @property
    def call(self):
        return self._call
    
class Debut(Thread):
    def __init__(self, Idolaccount, vote):
        super().__init__()
        self._Idolaccount=Idolaccount
        self._vote=vote
        
    def run(self):
        self._Idolaccount.addoil(self._vote)

def idol(name):
    idolaccount= Idolaccount()
    threads=[]
    for _ in range(100):
        t=Debut(idolaccount, 1)
        threads.append(t)
        t.start()
        
    for t in threads:
        t.join()
    print('%s has %d vote. Lets walk the flower path!\n一起走花路吧 ❀' %(name, idolaccount.call), end="\n")

idol("陈卓璇")
 
陈卓璇 has 100 vote. Lets walk the flower path!
一起走花路吧 ❀

 

 

陈卓璇 is my favorite trainee in the producer Camp 2020. While other girls are crying about judgements, she says “I never afraid of darkness, because true stars will shine ! ✨”

when others are doubt about the debut, she says “Halfway up on the hill is too crowded, We will meet on the top of the mountain !”

各自努力, 顶峰再见!

Happy studying!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: