day39--multithreaded instances, multi-wire locks

Source: Internet
Author: User
Tags class definition thread class

Python's locks can be extracted independently.

1 Mutex = Threading. Lock ()2# locks using 3# Create lock 4 mutex = Threading. Lock ()5# lock 6mutex.acquire ([timeout])7 # Release 8 mutex.release ()

Concept

Resource locking is not a resource lock, but a lock to lock resources, you can define multiple locks, like the following code, when you need to monopolize a resource, any lock can lock the resource

It's like you can lock the same one with different locks.

1 ImportThreading2 Import Time3       4Counter =05Counter_lock = Threading. Lock ()#just define a lock, not to lock the resources, you can define multiple locks, like the next two lines of code, when you need to occupy this resource, any lock can lock this resource6Counter_lock2 =Threading. Lock ()7Counter_lock3 =Threading. Lock ()8    9 #You can use any one of the top three locks to lock resourcesTen      One classMyThread (Threading. Thread):#use the class definition thread to inherit the threading. Thread A      def  __init__(self,name): -Threading. Thread.__init__(self) -Self.name ="thread-"+STR (name) the      defRun (self):#The run function must implement the -          GlobalCounter,counter_lock#multithreading is a shared resource, using global variables -Time.sleep (1);  -          ifCounter_lock.acquire ():#when an exclusive counter resource is required, it must be locked, which can be any one of the locks and can use any of the 3 locks defined above +Counter + = 1 -             Print "I am%s, set counter:%s"%(Self.name,counter) +Counter_lock.release ()#after using the counter resource, you must open the lock for other threads to use A                 at if  __name__=="__main__":    -      forIinchXrange (1,101):    -My_thread =MyThread (i) -My_thread.start ()

Thread is not secure:

One of the most common multithreaded small examples. I took a piece of the story, and I created a subclass mythread that inherits the thread class as our thread startup class. As a rule, rewrite the thread's Run method, which is called automatically when our thread starts up. So I first created 10 threads and added them to the list. Then use a For loop to turn on each thread. When using a For loop, call the Join method to wait for all threads to end before exiting the main thread.

This code may seem simple, but it actually hides a big problem, but it doesn't show up here. You really think I created 10 threads and sequentially called the 10 threads, and each thread added 1 to N. In fact, it is possible that a thread executes the n++, then the C thread executes the n++, and the B thread executes n++.

This involves a "lock" problem, if there are multiple threads operating an object at the same time, if the object is not well protected, it will cause the program results unpredictable (for example, we add a time.sleep (1) to the Run method of each thread, and output the thread name at the same time, we will find that The output will be messy. Because it is possible that one of our print statements prints only half the characters, the thread is paused and executes the other, so we see a messy result, which is called "thread unsafe".

Thread Lock:

So, the threading module provides us with a class, Threading.lock, lock. We create a class object, before the thread function executes, "preempt" the lock, after execution completes, "releases" the lock, we ensure that only one thread occupies the lock at a time. When you operate on a common object, there is no thread-insecure behavior.

So, we changed the code as follows:

1 #coding:uft-82 __author__='phtih0n'3 Importthreading, time4 classMyThread (Threading. Thread):5     def __init__(self):6Threading. Thread.__init__(self)7     defRun (self):8         GlobalN, Lock9Time.sleep (1)Ten         ifLock.acquire (): One             PrintN, Self.name An + = 1 - lock.release () - if "__main__"==__name__: then = 1 -Threadlist = [] -Lock =Threading. Lock () -      forIinchRange (1, 200): +t =MyThread () - threadlist.append (t) +      forTinchthreadlist: A T.start () at      forTinchthreadlist: -T.join ()

1Thread-2

2 Thread - 3 3 Thread - 4 4 Thread - 6 5 Thread - 7 6 Thread - 1 7 Thread - 8 8 Thread - 9 9 Thread - 5 Process finished with exit code  0

We see that we first set up a threading. Lock class object lock, in the Run method, we use Lock.acquire () to obtain this lock. At this point, the other threads will no longer be able to acquire the lock, and they will block the "if Lock.acquire ()" Here until the lock is freed by another thread: Lock.release ().

So, the content in the IF statement is a complete piece of code, and there is no longer a case of pausing to execute another thread in half execution. So the final result is neat.

Just as in Java, we use the Synchronized keyword to decorate a method that, in the same way, allows a piece of code to be executed by one thread without interrupting the jump to another thread.

This is the case when multithreading consumes a common object. If multiple threads are to invoke multiple phenomena, and a thread calls a lock to occupy the A object, B thread calls the B lock takes up the B object, a thread cannot invoke the B object, B thread cannot invoke the A object, and so waits. This creates a thread "deadlock".

In the threading module, there is also a class, Rlock, which is called a reentrant lock. The lock object is internally maintained with a lock and a counter object. The Counter object records the number of acquire, so that resources can be require multiple times. Finally, when all Rlock are release, other threads can get the resources. In the same thread, Rlock.acquire can be called multiple times, using this feature to resolve partial deadlock problems.

day39--multithreaded instances, multi-wire locks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.