We use the mutex (the Lock class object in Python) for thread synchronization:
Lock.acquire () equals p operation, gets a lock, locks
Lock.release () is equivalent to V operation, releasing a lock, releasing
1 #-*-coding:cp936-*-2 ImportThreading#Python implements multithreading primarily through the threading package in the standard library3 Import Time4 ImportOS5 6 7 defDochore ():#0.5s per call interval as interval8Time.sleep (0.5)9 Ten One defBooth (TID): A GlobalI - GlobalLock - whileTrue: theLock.acquire ()#get a lock, lock - ifI! =0: -i = I-1#sell a ticket to reduce one piece - Print(Tid,': now Left:'I#the number of votes left + Dochore () - Else: + Print("thread_id", Tid,"No More Tickets") AOs._exit (0)#exit procedures for tickets sold out atLock.release ()#Release Lock - Dochore () - - #Start of the main function -i= 15#initial number of votes -Lock = Threading. Lock () # Create lock in - #a total of 10 threads are set to forKinchRange (10): +New_thread = Threading. Thread (target=booth,args= (k,))#Creating threads; Python uses Threading.thread objects to represent threads -New_thread.start ()#call the Start () method to start the thread
We use global in our functions to declare variables as global variables, allowing multithreading to share I and lock (in C, we make it a global variable by placing variables out of all functions). If you do not declare this, because I and lock are immutable data Objects , they will be treated as a local variable. If it is a mutable data Object , then the global declaration is not required. We can even pass a mutable data Object as a parameter to the thread function. These threads will share these mutable data objects.
- Two dochore () functions were used in booth. The program can be improved in the future to allow threads to do more than i=i-1, such as printing the remaining votes, making money, or drinking saliva. The first Dochore () is still inside lock, so it is safe to use shared resources (critical operations, such as printing the remaining votes). At the second dochore (), lock has been released, so it is no longer possible to use a shared resource. This is where you can do things that don't use shared resources (Non-critical operation, like change, water). I deliberately let dochore () wait 0.5 seconds to represent the amount of time that these extra operations might take. You can define the function to replace Dochore ().
Python multithreading for ticketing