A critical resource is a resource that can only be accessed by one thread at a time, and a typical example is a printer, which can only be used by one program at a time to perform the printing function, since the code that accesses this part of the resource is often called a critical section.
1. Locking mechanism
Threading lock class, which is unlocked with the acquire function of the class and unlocked with the Realease function
ImportThreadingImport TimeclassNum:def __init__(self): Self.num=0 Self.lock=Threading. Lock ()defAdd (self): Self.lock.acquire ()#Lock and lock the appropriate resourcesSelf.num + = 1Num=self.num self.lock.release ()#unlock, leave the resource returnnum N=Num ()classJdthread (Threading. Thread):def __init__(Self,item): Threading. Thread.__init__(self) self.item=ItemdefRun (self): Time.sleep (2) Value= N.add ()#Add num 1 and output the original data and the data after +1 Print(Self.item,value) forIteminchRange (100): T=jdthread (item) T.start () T.join ()#make a thread one-by-one execution
2. Signal Volume
Semaphores also provide the Acquire method and the release method, each time the acquire method is called, if the internal counter is greater than 0, it will be reduced by 1, if the internal counter equals 0, it will block the thread, knowing that the wired thread calls the release method to update the internal counter to a greater than 1 position.
ImportThreadingImport TimeclassNum:def __init__(self): Self.num=0 Self.sem= Threading. Semaphore (value = 3) #allow up to three threads to access resources at the same time defAdd (self): Self.sem.acquire ()#internal counter minus 1Self.num + = 1Num=self.num self.sem.release ()#internal counter plus 1 returnnum N=Num ()classJdthread (Threading. Thread):def __init__(Self,item): Threading. Thread.__init__(self) self.item=ItemdefRun (self): Time.sleep (2) Value=N.add ()Print(Self.item,value) forIteminchRange (100): T=jdthread (item) T.start () T.join ()
3. Conditional judgment
The so-called conditional variable, that is, when a particular condition is met, the thread can access the relevant data.
It is done using the condition class, because it can also be used as a lock mechanism, so it also has the acquire method and the release method, and it also has the Wait,notify,notifyall method.
"""a simple production consumer model, through the control of the condition variable number of products to increase or decrease, call a producer product is +1, call a consumer product will be -1.""" """This is done using the Condition class, because it can also be used as a lock mechanism, so it also has the acquire method and the release method, and it also has the wait, notify, Notifyall method. """ ImportThreadingImportQueue,time,randomclassGoods:#Product Category def __init__(self): Self.count=0defAdd (Self,num = 1): Self.count+=NumdefSub (self):ifself.count>=0:self.count-= 1defEmpty (self):returnSelf.count <=0classProducer (Threading. Thread):#Producer Class def __init__(Self,condition,goods,sleeptime = 1):#sleeptime=1Threading. Thread.__init__(self) self.cond=condition Self.goods=Goods self.sleeptime=SleeptimedefRun (self): Cond=Self.cond Goods=Self.goods whileTrue:cond.acquire ()#Lock ResourcesGoods.add ()Print("Number of products:", Goods.count,"Producer Threads") Cond.notifyall ()#waking up all the waiting threads----is actually waking up the consumer processCond.release ()#Unlocking Resourcestime.sleep (self.sleeptime)classConsumer (Threading. Thread):#Consumer class def __init__(Self,condition,goods,sleeptime = 2):#sleeptime=2Threading. Thread.__init__(self) self.cond=condition Self.goods=Goods self.sleeptime=SleeptimedefRun (self): Cond=Self.cond Goods=Self.goods whileTrue:time.sleep (Self.sleeptime) cond.acquire ()#Lock Resources whileGoods.empty ():#Let the thread wait if there is no productcond.wait () goods.sub ( )Print("Number of products:", Goods.count,"Consumer Threads") cond.release ()#Unlocking Resourcesg=Goods () C=Threading. Condition () Pro=Producer (c,g) pro.start () con=Consumer (c,g) Con.start ()
4. Synchronization queue
The Put method and the Task_done method, the queue has an unfinished task number Num,put Num+1,task in turn num-1. The task ends when the task is complete.
ImportThreadingImportQueueImport TimeImportRandom" "1. Create an instance of Queue.queue () and populate it with data. 2. Pass the instance of the populated data to the thread class, which is inherited by the threading. Thread is created in the way. 3. Remove an item from the queue each time, and use the data in the thread and the Run method to perform the work accordingly. 4. After completing this work, use the Queue.task_done () function to send a signal to the queue that the task has completed. 5. Performing a join operation on a queue actually means waiting until the queue is empty before exiting the main program. " " classJdthread (Threading. Thread):def __init__(self,index,queue): Threading. Thread.__init__(self) self.index=Index Self.queue=QueuedefRun (self): whileTrue:time.sleep (1) Item=Self.queue.get ()ifItem isNone: Break Print("Serial Number:", Self.index,"Task", Item,"Complete") Self.queue.task_done ()#the Task_done method makes the number of outstanding tasks-1Q=queue. Queue (0)" "The initialization function accepts a number as the capacity of the queue, and if it passes a number less than or equal to 0, the capacity of the queue is assumed to be unlimited by default." " forIinchRange (2): Jdthread (I,q). Start ()#two threads to complete a task at the same time forIinchRange (10): Q.put (i)#the Put method makes the number of unfinished tasks +1
Four ways to synchronize python3.4 multithreading