Python 之 多线程同步(1)

1.利用LInux的互斥锁机制实现同步:

#
# A program to simulate selling tickets in multi-thread way
# Written by Rogen

#
# Import
#
import threading
import time
import os

#
# This function could be any function to do other chores.
#

def doChores():
    time.sleep(1)
#
# Function for each thread
#

class BoothThread(threading.Thread):
    def __init__(self, tid, monitor):
        self.tid = tid
        self.monitor = monitor
        threading.Thread.__init__(self)
    def run(self):
        while True:
            # Lock; or wait if other thread is holding the lock
            monitor['lock'].acquire()                          
            if monitor['tick'] != 0:
                # Sell tickets
                monitor['tick'] -=  1      
                # Tickets left    
                print(self.tid,':now left:',monitor['tick']) 
                # Other critical operations  
                doChore()                                      
            else:
                print("Thread_id",self.tid," No more tickets")
                os._exit(0)       
            # Unblock                             
            monitor['lock'].release()                          
            doChore()                                          # Non-critical operations

# Start of the main function
monitor = {'tick':50, 'lock':threading.Lock()}

# Start 10 threads
for k in range(10):
    new_thread = BoothThread(k, monitor)
    new_thread.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值