Threading module
Thread features:
Is asynchronous in nature, requiring multiple concurrent activities, the processing order of each activity may be uncertain, or is random and unpredictable, while the macro is running
Processes and threads of relationship:
Multitasking can be done by multiple processes, can also be done by multiple threads within a process, the process has a number of threads, a process has at least one thread. In the course of using threads it is generally recommended to use threading module, compared to some of the senior _thread. Many local threads and processes are the same
Thread threading module classes:
Attribute: name ------> name
ident -------> thread identifier
daemon -------> daemon thread identifier, the type bool
Methods: __ constructor init__ constructor, and the process is similar to the process can refer to the constructor
start: Start a thread
run: threading capabilities defined methods, usually redefined in the subclass
join: has been pending before starting the thread terminates, timeout is blocking time
Thread class to create a thread using three methods :( directly see examples)
① create a Thread class instance, he passed to a function
# 1, create a Thread class instance, it passed to a function # properties and methods of the thread DEF Task (task_id, task_time): Print ( " Start Task " , task_id, " AT " , ctime ()) SLEEP (task_time) Print ( " Task " , task_id, " DONE AT " , ctime ()) IF __name__ == " __main__ " : Print ( " ready to create thread " ) # create a thread class instance, it passed to a function, parameter passing is keyword arguments threading.Thread = t (target = Task, args = (1, 2 )) Print ( " ready to start a thread " ) # two settings daemon thread way, # daemon thread and daemon is the primary process finished running daemon ( line) process immediately end # t.setDaemon (True) t.daemon = True t.start () # name named to thread-N, N starts at 1 Print ( " thread's name: " , t.name) Print ( " thread of the above mentioned id: " , t.ident) Print ( " thread was already started . " )
② create a Thread instance, he passed to instantiate an object of a callable
# 2, create a Thread instance, he passed a callable instance of the class object # override method __call__ DEF Task (task_id, task_time): Print ( " Start Task " , task_id, " AT " , ctime () ) SLEEP (task_time) Print ( " Task " , task_id, " DONE AT " , ctime ()) # create a simple class class ThreadFunc (Object): DEF __init__ (Self, * args): . Super () __init__ () self.args = args #__call__ function to instantiate an object that is to be invoked DEF __call__ (Self, args *, ** kwargs): Task ( * self.args) IF the __name__ == " __main__ " : T = of the threading.Thread (target of ThreadFunc = (. 1 , 2 )) t.start () t.join ()
③ derived subclass of Thread, and create an instance of a subclass (recommended)
# 3、派生Thread的子类,并创建子类的实例(推荐) def task(task_id, task_time): print("start task", task_id, "at", ctime()) sleep(task_time) print("task", task_id, "done at", ctime()) class MyThread(threading.Thread): def __init__(self, *args): super().__init__() self.args = args def run(self): task(*self.args) IF __name__ == " __main__ " : myThread = MyThread (1, 2 ) # use the difference here is not to call the run method, and the process is not myThread.start () myThread.join ()
The state of the thread (typically after simplification)
1. Create (NEW): create a new thread object.
2. run (RUNNABLE): After the thread object is created, other threads (such as main thread) calls the start () method of the object. The thread state is located runnable threads in the pool, waiting to be selected thread scheduling, acquiring the right to use the cpu.
3. Run (RUNNING): runnable (Runnable) obtained threads of cpu time slice (timeslice), execution of program code.
4. blocked (BLOCKED): blocking state is the thread for some reason to give up the right to use the cpu, that is let out of the cpu timeslice, temporarily stop running. Until the thread becomes runnable (runnable) state, you have a chance to get cpu timeslice to run (running) state again. Case of obstruction of three categories:
. (A) wait for blocking: sleep
(B) synchronous blocking: thread running (running) when acquiring synchronization lock object, if the synchronization lock is occupied by another thread.
5. Death (DEAD): Thread run (), main () method has finished executing, or due to abnormal withdrew from the run () method, the thread end of the life cycle. Thread of death can not be resurrected again.
FIG switching state:
Summary: In multiple threads of a process can share global variables of the process, but if multiple threads simultaneously modify the global variable, it may cause confusion to global variables between multiple threads (ie threads is unsafe) next it is necessary talked about the lock mechanism.