Python Learning Note 16: Standard library Multithreading (threading package)

Source: Internet
Author: User

Python mainly uses the standard library threading package to implement multithreading.
Today, the Internet age, all servers you will receive a large number of requests.

The server will take advantage of multithreading to handle these requests in order to improve the read and write efficiency of the network port.
Python It is a Web server background working language (Douban), so multithreading is naturally supported by the Python language.



Multi-threaded ticketing and synchronization we use Python to implement the ticketing procedures in Linux multi-threading and synchronization.


We use a mutex (that is, the lock class object in Python) to implement thread synchronization:

Import Threadingimport Timeimport os# This function could is called by any function to does other Chores.def Dochore (): t                Ime.sleep (0.5) # Function for each threaddef booth (TID): Global I Global lock while True:lock.acquire () # Lock;            Or wait if other thread is holding the lock if I! = 0:i = i-1 # Sell Tickets            Print (TID, ': Now left: ', i) # Tickets left Dochore () # Other critical operations else: Print ("thread_id", Tid, "No more Tickets") Os._exit (0) # exit the whole process Immediat Ely Lock.release () # Unblock Dochore () # non-critical operations# Start of The main functioni = # Available Ticket Number lock = Threading. Lock () # lock (i.e., mutex) # Start Threadsfor K in range: New_thread = Threading. Thread (target=booth,args= (k,)) # Set up threAd                                      Target:the callable (function) to is run, args:the argument for the callable New_thread.start () # Run the thread

There are two global variables, one is I, which is used to store the number of votes remaining. One is the lock object, which synchronizes the change of the thread to I.
In addition In the final for loop, we set up 10 threads altogether.

Each of the threads runs the booth () function.
The thread is formally started when the start () method is called (in fact, there are up to 11 threads in the computer.) Because the main program itself consumes a single thread).


Python uses the Threading.thread object to represent the thread and uses the Threading.lock object to represent a mutually exclusive lock (mutex).

There are two points to note:
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).


Assume that 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. We used two dochore () functions in booth.


Able to improve the program in the future. In order to let the thread in addition to I=i-1, do a lot of other operations, such as printing the remaining votes, change, or drink saliva and so on.


The first Dochore () is still inside of lock. So it is safe to use shared resources (critical operations, for example, to print the remaining votes).
A second dochore (). Lock has been released, so it is no longer possible to use shared resources.
This is the time to do things that do not use shared resources (Non-critical operation, for example, change, water).


It's good to have Dochore () wait for 0.5 seconds. To represent the amount of time that these additional operations may take.

You can define the function to replace Dochore ().




The Python program above the OOP creation thread is very similar to a procedure-oriented C program.

We describe how to implement multi-threading through an object-oriented approach, with the core of inheriting threading. Thread class.


Import threadingimport timeimport os def dochore (): Time.sleep (0.5) # Function for each threadclass booththread (Threadi Ng. Thread): Def __init__ (self, Tid, monitor): Self.tid = tid self.monitor = Monitor Threadin                          G.thread.__init__ (self) def run (self): while true:monitor[' Lock '].acquire () # Lock; Or wait if other thread is holding the lock if monitor[' tick ']! = 0:monitor[' tick '] = monitor['                Tick ']-1 # Sell Tickets print (Self.tid, ': Now left: ', monitor[' Tick ']) # tickets left Dochore () # Other critical Operations Else:print ("Thr Ead_id ", Self.tid," No more Tickets ") Os._exit (0) # exit the whole proces                            s immediately monitor[' lock '].release () # Unblock Dochore ()              # non-critical Operations # Start of the main functionmonitor = {' Tick ': +, ' Lock ': Threading. Lock ()} # Start ten threadsfor K in range: New_thread = Booththread (k, monitor) New_thread.start ()

Threading has been used in the for loop above. Thread () method to create a thread object and pass the function booth () and its parameters to the modified object, and call the start () method to execute the thread.
Oop words. Define the command that the thread will run by altering the run () method of the thread class.
A class booththread has been customized, and this class inherits from thread. Threading class.


We then put the actions of the above booth () into the run () method of the Booththread class.
Attention. Instead of using global variables to declare the global variable, we used a dictionary monitor to store the globals and then passed the dictionary as a parameter to the thread function.
Because the dictionary is a mutable data object. So when it is passed to the function, the function is still using the same object, which is equivalent to being shared by multiple threads.
This is also a technique for multithreading and even multi-process programming (you should try to avoid using the global declaration above as it does not apply to the Windows platform).
There is no significant difference between OOP programming methods and process-oriented programming methods.

Other threading. Thread object, we have introduced the object's start () and run (), in addition:
Join () method
The thread that calls the method waits until it finishes modifying the thread object. Resume execution again. This is similar to calling the wait () function between processes.


The following objects are used to handle multi-threaded synchronization.

Once the object is created. Can be shared by multiple threads and block certain processes according to the situation.




Threading. Lock Object
Mutex, with the acquire () and release () methods.




Threading. Condition Object
Condition variable, when the object is established. Will include a lock object (since condition variable is always used with the mutex).
The ability to invoke the acquire () and release () methods on the condition object to control the potential lock object.


Wait () method
Equivalent to Cond_wait ()


Notify_all ()
Quite with Cond_broadcast ()


Nofify ()
Similar to the Notify_all () feature, but only wakes up a waiting thread, not all


Threading. Semaphore Object
Semaphore, which is the count lock.

When you create an object. Ability to pass an integer as the upper limit of the count (Sema = threading. Semaphore (5)).


It is similar to lock and has two methods for lock.




Threading. Event Object
With threading. Similar to the condition phase. Equivalent to condition variable without potential lock protection.


The object has a status of true and false two.

You can wait for multiple threads to use Wait (). The object is set to true until a thread calls the object's set () method.

The thread can call the object's clear () method to reset the object to a false state.


# These chapters have not been seen so clearly how ~~~~~

Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Python Learning Note 16: Standard library Multithreading (threading package)

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.