Python creates a thread to implement the ticketing system, and python object-oriented
--- Restore content start ---
PassObject-orientedThe core of Multithreading is inheritance.Threading. ThreadClass. We have defined a class.BoothThread, This classInherited from the thread. Threading class, by modifyingRun ()Method to define the command to be executed by the thread.
1 import threading # Python mainly uses the threading package in the standard library to implement multithreading 2 import time 3 import OS 4 5 # As an interval of 0.5 s 6 def doChore (): 7 time. sleep (0.5) 8 9 # define a class BoothThread to inherit from the thread. threading class 10 class BoothThread (threading. thread): 11 def _ init _ (self, tid, monitor): 12 self. tid = tid13 self. monitor = monitor14 threading. thread. _ init _ (self) 15 def run (self): 16 while True: 17 monitor ['lock']. acquire () # Call lock. acqu Ire () locks 18 if monitor ['tick']! = 0: 19 monitor ['tick'] = monitor ['tick']-1 # A 20 print (self. tid, ': now left:', monitor ['tick']) # number of remaining votes 21 doChore () 22 else: 23 print ("Thread_id", self. tid, "No more tickets") 24 OS. _ exit (0) # exit program 25 monitor ['lock'] After the ticket is sold out. release () # release lock 26 doChore () 27 28 29 monitor = {'twick': 20, 'lock': threading. lock ()} # Number of initialization votes 30 31 # A total of 10 threads are set 32 for k in range (10): 33 new_thread = BoothThread (k, monitor) # create thread; python uses threading. thread object to represent the thread class BoothThread inherited from Thread. threading Class 34 new_thread.start () # Call the start () method to start the thread
Here we useDictionaryMonitor stores global variables and passes the dictionary as a parameter to the thread function. Because the dictionary isVariable data objectSo when it is passed to the function, the function still uses the same object, which is equivalent to being shared by multiple threads.