---restore content starts---
Multi-Threading is implemented through an object-oriented approach, with the core of inheriting threading. Thread class. We define a class Booththreadourselves, which inherits from thread. The threading class defines the command to be executed by a thread by modifying the run () method of the thread class.
1 ImportThreading#Python implements multithreading primarily through the threading package in the standard library2 Import Time3 ImportOS4 5 #0.5s per call interval as interval6 defDochore ():7Time.sleep (0.5)8 9 #define a class booththread inherit from the Thread.threading classTen classBooththread (Threading. Thread): One def __init__(self, Tid, monitor): ASelf.tid =Tid -Self.monitor =Monitor -Threading. Thread.__init__(self) the defRun (self): - whileTrue: -monitor['Lock'].acquire ()#call Lock.acquire () locking - ifmonitor['Tick'] !=0: +monitor['Tick'] = monitor['Tick']-1#sell a ticket to reduce one piece - Print(Self.tid,': now Left:', monitor['Tick'])#the number of votes left + Dochore () A Else: at Print("thread_id", Self.tid,"No More Tickets") -Os._exit (0)#exit procedures for tickets sold out -monitor['Lock'].release ()#Release Lock - Dochore () - - inMonitor = {'Tick': 20,'Lock': Threading. Lock ()}#initial number of votes - to #a total of 10 threads are set + forKinchRange (10): -New_thread = Booththread (k, monitor)#Creating threads; Python uses the Threading.thread object to represent the thread class Booththread inherits from the Thread.threading class theNew_thread.start ()#call the Start () method to start the thread
A dictionary Monitor is used to store the global variables, and the dictionary is passed as a parameter to the thread function. Since the dictionary is a mutable data Object , when it is passed to the function, the function is still using the same object, which is equivalent to being shared by multiple threads.
Python creates an object-oriented way to implement the ticketing system for threading