python 多线程 - 售票

1. 多线程使用

  • 多线程共享全局变量,利用互斥锁解决资源竞争
# -*- coding: utf-8 -*-
import threading
import time
import os


def sell_ticket(tid):
    """售票"""
    global num
    while True:
        lock.acquire()          # 互斥锁
        if num != 0:
            num = num - 1
            print("Thread_id: {} 剩余售票: {}".format(tid, num))
            time.sleep(0.5)
        else:
            print("Thread_id: {} 票已售空".format(tid))
            os._exit(0)         # 票售完,退出程序
        lock.release()          # 释放锁
        time.sleep(0.5)

num= 15                         # 初始化票数
lock = threading.Lock()         # 创建锁


if __name__ == '__main__':
    # 设置了5个线程
    for i in range(5):
        t = threading.Thread(target=sell_ticket, args=(i,))
        t.start()
posted @ 2021-09-28 18:58  tt_贝塔  阅读(113)  评论(0编辑  收藏  举报