python 多线程

时间:2022-05-27 23:14:24   收藏:0   阅读:61

1. 多线程使用

# -*- coding: utf-8 -*-
import threading
import time
import os


def booth(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=booth, args=(i,))
        t.start()

原文:https://www.cnblogs.com/test-works/p/15349409.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!