python 线程加锁示例

import threading
from threading import Thread, Lock
import time

ticket = 50
lock_obj = Lock()


def sale_ticket():
    global ticket
    for i in range(100):
        lock_obj.acquire() # 上锁
        if ticket > 0:
            print(f'{threading.current_thread().name}正在出售第{ticket}张票')
            ticket -= 1
        time.sleep(1)
        lock_obj.release() # 解锁


if __name__ == '__main__':
    for i in range(3):
        t = Thread(target=sale_ticket)
        t.start()

 

posted @ 2024-08-23 13:39  龍飛鳯舞  阅读(1)  评论(0编辑  收藏  举报