《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.8 KiB

  1. #coding=utf-8
  2. import threading
  3. import random
  4. import time
  5. class SemaphoreThread(threading.Thread):
  6. """classusing semaphore"""
  7. availableTables=['A','B','C','D','E']
  8. def __init__(self,threadName,semaphore):
  9. """initialize thread"""
  10. threading.Thread.__init__(self,name=threadName)
  11. self.sleepTime=random.randrange(1,6)
  12. #set the semaphore as a data attribute of the class
  13. self.threadSemaphore=semaphore
  14. def run(self):
  15. """Print message and release semaphore"""
  16. #acquire the semaphore
  17. self.threadSemaphore.acquire()
  18. #remove a table from the list
  19. table=SemaphoreThread.availableTables.pop()
  20. print "%s entered;seated at table %s." %(self.getName(),table),
  21. print SemaphoreThread.availableTables
  22. time.sleep(self.sleepTime)
  23. #free a table
  24. print " %s exiting;freeing table %s." %(self.getName(),table),
  25. SemaphoreThread.availableTables.append(table)
  26. print SemaphoreThread.availableTables
  27. #release the semaphore after execution finishes
  28. self.threadSemaphore.release()
  29. threads=[] #list of threads
  30. #semaphore allows five threads to enter critical section
  31. threadSemaphore=threading.Semaphore(len(SemaphoreThread.availableTables))
  32. #创建一个threading.Semaphore对象,他最多允许5个线程访问临界区。
  33. #Semaphore类的一个对象用计数器跟踪获取和释放信号机的线程数量。
  34. #create ten threads
  35. for i in range(1,11):
  36. threads.append(SemaphoreThread("thread"+str(i),threadSemaphore))
  37. #创建一个列表,该列表由SemaphoreThread对象构成,start方法开始列表中的每个线程
  38. #start each thread
  39. for thread in threads:
  40. thread.start()