Python Multithreading
Multithreading is similar to executing several different programs at the same time, multithreaded operation has the following advantages:
- Threads can be used to place tasks that occupy a long period of time in the background to be processed.
- User interface can be more attractive, such as the user clicked a button to trigger the processing of certain events, you can pop up a progress bar to show the progress of processing
- The program may run faster
- Threads are useful for tasks such as user input, file read and write, and network send and receive data. In this case we can release some precious resources such as memory footprint and so on.
Threads are still different from the process during execution. Each separate thread has a program run entry, sequence of sequence execution, and exit of the program. However, threads cannot be executed independently, and must be dependent on the application, which provides multiple threads of execution control.
Each thread has his own set of CPU registers, called the thread's context, which reflects the state of the CPU register on which the thread last ran the thread.
The instruction pointer and stack pointer registers are the two most important registers in the thread context, and threads are always run in the context of the process, which is used to flag memory in the process address space of the owning thread.
- The thread can be preempted (interrupted).
- Threads can be shelved (also known as sleep) while other threads are running-this is the thread's retreat.
There are two ways to use threads in Python: A function or a class to wrap a thread object.
Function: Call the Start_new_thread () function in the thread module to generate a new thread. The syntax is as follows:
thread.start_new_thread ( function, args[, kwargs] )
Parameter description:
- function-thread functions.
- Args-arguments passed to the thread function, he must be a tuple type.
- Kwargs-Optional parameters.
Instance:
#!/usr/bin/python#-*-coding:utf-8-*-ImportThreadImport Time#define a function for a threaddefprint_time (ThreadName, delay): Count=0 whileCount < 5: Time.sleep (delay) Count+ = 1Print "%s:%s"%(ThreadName, Time.ctime (Time.time ()))#Create two threadsTry: Thread.start_new_thread (Print_time, ("Thread-1", 2, ) ) Thread.start_new_thread (Print_time, ("Thread-2", 4, ) )except: Print "error:unable to start thread" while1: Pass
The end of a thread is generally dependent on the natural end of the thread function, or thread.exit () can be called in an inline function, and he throws Systemexit exception to exit the thread.
Python provides support for threads through the two standard library thread and threading. The thread provides a low-level, primitive thread, and a simple lock.
Other methods provided by the thread module:
- Threading.currentthread (): Returns the current thread variable.
- Threading.enumerate (): Returns a list that contains the running thread. Running refers to threads that do not include pre-and post-termination threads until after the thread has started and ends.
- Threading.activecount (): Returns the number of running threads with the same result as Len (Threading.enumerate ()).
In addition to using methods, the thread module also provides the thread class to handle threads, and the thread class provides the following methods:
- run (): the method used to represent thread activity.
- Start (): initiates thread activity.
- join ([TIME]): waits until the thread aborts. This blocks the calling thread until the thread's join () method is called abort-gracefully exits or throws an unhandled exception-or an optional timeout occurs.
- isAlive (): Returns whether the thread is active.
- getName (): returns the thread name.
- setName (): sets the thread name.
python-Multithreading: Calling the Start_new_thread () function in the thread module to generate a new thread