"Python Standard library Learning" thread,threading (a) introduction and use of multithreading

Source: Internet
Author: User
Tags stack trace thread class

In a single program we often use multithreading to deal with different tasks, especially some jobs need to wait, then we will create a new thread to wait and then do some operations, when done after the thread exit is recycled. When a program runs, a process is created by the system, and a thread runs, which is the main thread, main, and the new threads created in the main thread are child threads, and the child threads usually do some auxiliary work. The thread and threading two modules are available in Python to support multithreading. This article describes the multi-threaded and basic use of Python, the next article on Python multithreading synchronization problem.

There are two ways to use threads in Python, the first is to use the Start_new_thread function of the thread module, and the other is to wrap the thread object with the threading module's thread class.

1. Using the thread module

Use the Start_new_thread function of the thread module to create a thread and start. Start_new_thread function Prototypes:

Thread.start_new_thread (function, args[, Kwargs])

>>> Help (Thread.start_new_thread) to built-in function start_new_thread in module Thread:start_new_thread (...)    Start_new_thread (function, args[, Kwargs])    (Start_new () is an obsolete synonym)        start a new thread and return its identifier.  The thread would call the    function with positional arguments from the tuple args and keyword arguments    taken from t He optional dictionary Kwargs.  The thread exits when the    function returns; The return value is ignored.  The thread would also exit when the    function raises an unhandled exception; a stack trace would be    

  

This function creates a new thread and immediately executes the function Function,args is the parameter of the function, is a tuple, and Kwargs is optional, which provides a dictionary of named arguments for the function. The function returns an integer that is the thread identifier. The thread exits gracefully when the function is finished executing, and the thread exits unexpectedly if there are unhandled exceptions during execution.

The main functions of the thread module are:

1). Start_new_thread ()

Creates and starts a thread execution function, the function finishes executing a thread exit, or encounters an unhandled exception thread exiting unexpectedly.

2). Thread.exit ()

Ends the current thread, triggers a systemexit exception, and if no catch handles the exception, the thread exits.

3). Thread.get_ident ()

Gets the identifier of the thread, which is the identifier returned when the new thread was created, is an integer.

4). Thread.interrupt_main

Triggers a keyboardinterrupt exception in main thread main, which is used by the child thread to terminate the main thread.

5). Thread.allocate_lock ()

Creates a lock object LockType that enables multiple threads to synchronize access to shared resources.

Using multithreading in Python is more of a second way of using the threading module.

2. Using the Threading module

The

        Threading module is the second encapsulation of the thread module and provides a better API for us to use. Using threading to implement multithreaded programming is a thread class, or a timer class, a timer is a subclass of thread, and you can specify a time interval after an action is performed:

  1  from  threading import   Timer   2   3   4   5  def   main ():   6   7  print   " Span style= "COLOR: #800000" >timer test!   "  8   9  t = Timer (3 , Main)  10  11  t.start () 

There are two ways to use the thread class, one is to create an instance of the thread class directly, and the other is to customize the class to inherit the thread class. Using an instance of the thread class, in its initialization function __init__ the callable object as a parameter, and the thread's initialization function __init__ prototype:

__init__ (self, group=none, Target=none, Name=none, args= (), Kwargs=none, Verbose=none);

Group and verbose do not know what it is, target is a callable object, the thread starts to execute it, name is the name of the thread, the default is "Thread-n", N is the number, and args and Kwargs are the parameter list and keyword arguments that call target.

1  from Import Thread 2 3 def Main (A, b): 4 5     Print ' a:%d, b:%d ' % (A, b)67 Thread (target=main, name='newthread ', args= (1, 2). Start ()

Custom classes to inherit the thread class, and then override the Run method to implement our own operations.

 fromThreadingImportThreadclassMyThread (Thread):def __init__(self, threadname, A, b): Thread.__init__(Self, name=threadname) SELF.A=a self.b=bdefRun (self):Print 'a:%d, b:%d'%(SELF.A, self.b) MyThread= MyThread ('Newthread', 1, 2) Mythread.start ()

The logic code is written in the Run method, but we start the thread is to use the Start method, the two methods are different, if the direct call to the run () method, but simply call the method, and call the start () method is to start the thread from the new state programming ready state, waiting for the CPU scheduling, This involves several states of the thread, start () after the thread does not run immediately but programming ready state, when the CPU time slice after the programming run state, when the run method ends or there are unhandled exceptions, the thread ends into a dead state waiting to be recycled, In the running state, if the resource is not ready, it will become blocked, and once the resource is available, the programming readiness state waits for the CPU to dispatch.

Main classes of the threading module:

1). Thread class

Already described above.

2). Timer class

The subclass of thread, as described above.

3). Lock,rlock,condition class

Synchronous lock, which is used to realize the problem of thread synchronization and resource sharing.

4). Event class

For multithreaded communication.

Multi-threaded synchronous lock lock,rlock,condition and multi-threaded communication event are later introduced in multithreading synchronization.

Threading module The main function of the thread class:

1). Thread.getname (), Thread.setname ()

Gets and sets the thread name.

2). Thread.ident ()

Gets the identifier of the thread, which is an integer.

3). Thread.is_alive (), thread.isalive ()

Determines if the thread is alive, that is, whether the thread has ended.

4). Thread.activecount ()

Gets the total number of threads currently alive, including the main thread main.

5). Thread.Join ()

Causes the main thread to block, knowing that the child thread is finished or timed out, that it has a parameter of timeout that indicates a time-out, and defaults to none.

6). Thread.setdaemon ()

A parameter with a Boolean value that defaults to False, which sets whether the child thread ends with the main thread.

Look at the Join method and the Setdaemon method:

Importthreading, timeclassMyThread (Threading. Thread):def __init__(self): threading. Thread.__init__(self)defRun (self):Print 'Thread Start'Time.sleep (3)        Print 'Thread End'Thread1=MyThread () Thread1.start () Time.sleep (1) Print 'start Join'#Thread1.join ()Print 'End Join'

Output Result:

Do not add Thread.jointhread startstart joinend jointhread end plus thread.jointhread startstart jointhread endend Join

The main thread of sleep (1) A second is to allow the thread to be dispatched, the thread in Sleep (3) Three seconds is to let the main thread end, from the output results of the two cases can see the function of join.

Import threading, Time  class MyThread (threading. Thread):     def __init__ (self):        threading. Thread.__init__ (self)     def run (self):        print ' thread start '        time.sleep (3)        print ' Thread end '  print ' main start ' thread1 = MyThread () #thread1. Setdaemon (True) Thread1.start () time.sleep (1) print ' main End '

Output Result:

Setdaemon default is Falsemain startthread startmain endthread end Setdaemon set to Truemain startthread Startmain end

  

As can be seen from the printed result, when set to true, the thread is still in the sleep process is over, so that the thread end of the sentence is not printed out.

Of course, the thread class is more than these methods, these are just common methods, through Help (thread) can be viewed.

"Python Standard library Learning" thread,threading (a) introduction and use of multithreading

Related Article

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.