The difference between threads and processes is that they share status, memory, and resources. For a thread, this simple difference is both its advantage and Its disadvantage. On the one hand, threads are lightweight and easy to communicate with each other, but on the other hand, they also bring about various problems including deadlocks, contention conditions and high complexity. FortunatelyGilCompared with the queue module, the Python language is much less complex in thread implementation than other languages.
Global interpreter lock indicates that the python interpreter is NOT thread-safe. The current thread must hold a global lock for secure access to Python objects. Because only one thread can obtain the python object/c api, the interpreter regularly releases and reacquires the lock every time it passes through 100 bytecode instructions. The interpreter can check the thread switching frequency through the SYS. setcheckinterval () function.
It should be noted that due to Gil, CPU-limited applications will not benefit from the use of threads. We recommend that you use processes or create processes and threads in a hybrid manner when using python.
To use a thread in Python, Python lib provides two methods.One is a function type, and the other is a thread object encapsulated by a class.
For more information about multithreaded programming, such as mutex, semaphore, and critical section, see the python documentation and related materials.
Next, let's take a look at the two methods of multi-thread programming using python.
Function Type
Call the start_new_thread () function in the thread module to generate a new thread. The sample code is as follows:
#!/usr/bin/env python
# encoding: utf8
import time
import thread
def timer(no, interval):
""""""
print 'Thread :(%d) Time:%s'%(no,time.ctime())
time.sleep(interval)
print 'Thread :(%d) End.'%no
def test():
""""""
thread.start_new_thread(timer,(1,1))
thread.start_new_thread(timer,(2,3))
time.sleep(5)
if __name__ == '__main__':
test()
This is thread. start_new_thread (function, argS [, kwargs]) function prototype. The function parameter is the thread function to be called. The args parameter is the parameter that is passed to your thread function, it must be of the tuple type, and kwargs is an optional parameter. The end of a thread generally ends naturally by the thread function. You can also call thread. Exit () in the thread function to throw systemexit exception to exit the thread.
Inheritance type
The threading module is called to inherit the threading. Thread class to encapsulate a thread object. The sample code is as follows:
#! /Usr/bin/ENV Python
# Encoding: utf8
Import threading
Import time
Class timer (threading. Thread): # My Timer class inherits from the threading. Thread class.
Def _ init _ (self, no, interval ):
# When I override the _ init _ method, remember to call the _ init _ method of the base class.
Threading. thread. _ init _ (Self)
Self. No = No
Self. interval = Interval
Def run (Self): # rewrite the run () method and put the code of your thread function here
Print 'thread object % s (% d), time: % s' % (self. getname (), self. No, time. ctime ())
Time. Sleep (self. interval)
Def test ():
Threadone = timer () # generate two thread objects
Threadtwo = timer (2, 3)
Threadone. Start () # activate a thread by calling the. Start () method of the thread object
Threadtwo. Start ()
If _ name __= = '_ main __':
Test ()
Multi-thread Analysis
Getname () is a method of the threading. Thread class to obtain the name of this thread object. Another method, setname (), is to set the name of the thread object.
- To create a thread, you must first create a thread object: threadone = timer (). After a thread object is created, it is in theBorn"(Birth status)
- Start the thread and call the START () method of the thread object: mythread1.start () is now in theReady"Status or"Runnable"Status.
- The thread is in the"Sleep"Status
- Generally, when the run method of the thread object ends or an exception is thrown during execution, the thread will end andDead"Status. The system automatically clears the "dead" status thread.
- If one thread T1 needs to wait until the execution of the other thread T2 ends before it can run, then the join () method of T2 can be called in T1.
- If the main thread of a process is finished and the sub-thread is still running, the process will not exit until all sub-threads are finished.
How can other sub-threads exit when the main thread ends? Use the setdaemon () method of the thread object. The parameter is of the bool type. If it is true, you will be obedient. If it is true, the boss (the main thread) will call and you will also withdraw from the system. If it is false, you don't have to be so obedient. The boss allows you to fight for something that will not happen.Note that the setdaemon () method must be called before the thread object does not call the START () method. Otherwise, it will not work..
t1 = mythread('t1')
print t1.getName(),t1.isDaemon()
t1.setDaemon(True)
print t1.getName(),t1.isDaemon()
t1.start()
print 'main thread exit'
Obtain thread-related information
A. Get the reference of the currently running thread
running = threading.currentThread()
B. obtain a list of all the currently active objects (that is, any threads that start the run method but are not terminated ).
threadlist = threading.enumerate()
C. Obtain the length of the list
threadcount = threading.activeCount()
D. Check the status of a thread object and call the isalive () method of this thread object. If the return value is 1, it indicates that the thread object is in the runnable State and there is no "dead"
threadflag = threading.isAlive()