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()