Basic Python Learning (ix)

Source: Internet
Author: User
Tags thread class

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.

Threads can be divided into:

    • kernel thread: created and revoked by the operating system Kernel.
    • user thread: a thread implemented in a user program that does not require kernel Support.
Python threads

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/env python#-*-coding:utf-8-*-#Author:jerry ShiImport_threadImport 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
Threading Module

Python3 provides support for threading through two standard libraries _thread and Threading.

_thread provides a low-level, primitive thread, and a simple lock, which is relatively limited compared to the threading Module.

The Threading module provides additional methods in addition to all the methods in 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 (): Set thread name
Creating a thread using the threading module

We can pass directly from Threading. Thread inherits the creation of a new subclass, and after instantiation invokes the start () method to start a new thread, that is, it invokes the Thread's run () method:

#!/usr/bin/env python#-*-coding:utf-8-*-#Author:jerry ShiImportThreadingImportTimeexitflag=0classMyThread (threading. Thread):def __init__(self, threadID, name, counter): threading. Thread.__init__(self) Self.threadid=ThreadID Self.name=name Self.counter=counterdefRun (self):Print("Start Thread:"+self.name) print_time (self.name, self.counter,5)        Print("to Exit a thread:"+Self.name)defprint_time (threadname, delay, counter): whilecounter:ifexitFlag:threadName.exit () time.sleep (delay)Print("%s:%s"%(threadname, time.ctime (time.time () ))) counter-= 1#Create a new threadThread1 = MyThread (1,"Thread-1", 1) Thread2= MyThread (2,"Thread-2", 2)#Open new Threadthread1.start () thread2.start () thread1.join () thread2.join ( )Print("Exit main thread")

Basic Python Learning (ix)

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.