Python第四周之多线程和多进程之线程加锁、五车争霸赛

# Information Technology
# 摩尔定律 -- 任何买不起的电子产品,在18月后价格会降低一半,甚至更多。
# 原因:电子产品每隔18个月,性能会翻翻。
# 安迪比尔定律:安迪给你的东西,比尔都会给你拿走。硬件性能起来了,但是软件跟不上。
# 所以:当软件更新时,硬件的性能需求将会提升。
# 反摩尔定律:一个IT公司如果今天和18个月前卖掉同样多的、同样的产品,它的营业额就要降一半。IT界把它称为反摩尔定律。
# 线程加锁
import
time from threading import Thread, Lock class Account(object): def __init__(self): self._balance = 0 self._lock = Lock() @property def balance(self): return self._balance def deposit(self, money): """当多个线程同时访问一个资源的时候,就有可能因为竞争资源导致状态崩溃 被多个线程访问的资源,称为临界资源,对临界资源的访问需要加上保护。 """ if money: self._lock.acquire() # 加锁,开始是并行,加锁后变成串行,解锁后变成并行。 try: new_balance = self._balance + money time.sleep(0.01) self._balance = new_balance finally: self._lock.release() class AddMoneyThread(Thread): def __init__(self, account): super(AddMoneyThread, self).__init__() self._account = account def run(self): self._account.deposit(1) def main(): account = Account() tlist = [] for _ in range(100): t = AddMoneyThread(account) tlist.append(t) t.start() for t in tlist: t.join() print('%d元' % account.balance) if __name__ == '__main__': main()

五车争霸赛

from random import randint
from threading import Thread

import pygame
import time


class Color(object):
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GRAY = (242, 242, 242)

    @staticmethod
    def random_color():
        r = randint(0, 255)
        g = randint(0, 255)
        b = randint(0, 255)
        return r, g, b


class Car(object):

    def __init__(self, x, y, color):
        self._x = x
        self._y = y
        self._color = color

    def move(self):
        if self._x <= 870:
            self._x += randint(1, 10)
            return True
        return False

    def draw(self, screen):
        pygame.draw.rect(screen, self._color, [self._x, self._y, 80, 40], 0)


def main():

    class BackgroundThread(Thread):

        def run(self):
            nonlocal screen
            is_go_on = True
            while is_go_on:
                screen.fill(Color.GRAY)

                pygame.draw.line(screen, Color.BLACK, (130, 0), (130, 600), 4)
                pygame.draw.line(screen, Color.BLACK, (950, 0), (950, 600), 4)
                for car in cars:
                    car.draw(screen)
                pygame.display.flip()
                time.sleep(0.05)
                for car in cars:
                    if not car.move():
                        is_go_on = False

    cars = []
    for i in range(5):
        temp = Car(50, i * 120 + 50, Color.random_color())
        cars.append(temp)

    pygame.init()
    screen = pygame.display.set_mode((1000, 600))
    pygame.display.set_caption('五车争霸赛')
    BackgroundThread(daemon=True).start()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    pygame.quit()


if __name__ == '__main__':
    main()
 
原文地址:https://www.cnblogs.com/zl666/p/8638413.html