Python Learning---threading learning 1220

Source: Internet
Author: User
Tags thread class

Threading Basics

What are threads (thread)

A thread is the smallest unit that a CPU Scheduler can perform operations on. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process [in other words, a thread is a collection of instructions], one process can be concurrent with multiple threads, and each thread performs different tasks in parallel

Execution characteristics of threads

A thread has only 3 basic states: Ready, execute, block.

Threads have 5 basic operations to toggle the state of a thread: derive, block, activate, dispatch, end.

What are processes (process)
Process, which is the basic unit that the operating system allocates and manages resources in the course of executing, is a dynamic concept, which is the basic unit of computer system resources. Each process has its own address space, either process space or (virtual space). The size of the process space is only related to the number of processor bits

Process to open a child process, the child process completely copy the parent process, such as the parent process occupies 20M, the child process also occupies 20M, so the open process is more resource -consuming than the thread

The difference between a thread and a process

The thread shares the address space of the process that created it; The process has its own address space.

Threads can access data segments of their processes directly; The process owns its own copy of the data segment of its parent process.

A thread can communicate directly with other threads of its process; The process must communicate with the sibling process using interprocess communication.

New threads are easy to create; The new thread needs to repeat the parent thread. For example, the parent process consumes 20M and the child process consumes 20M, so the process consumes more resources than the thread.

Threads can operate between each other, and processes cannot be

Changes to the main thread (cancellation, priority changes, and so on) may affect other child thread threads of the process; Changes to the parent process do not affect child processes.

Q: Is the thread execution fast or the execution process fast? [Trap problem]

Answer: Same fast, run the same content

Python can create multiple processes, not strictly because there are gil,python not multi-threading, but can take advantage of multiple processes to solve [multi-process can not achieve data sharing, can be achieved through other solutions, co-processes, heap and other scenarios] to achieve CPU multi-core utilization

If in the PY, the task is IO-intensive [not always call the CPU to perform tasks, there will be sleep and other IO blocking], multi-threading, if computationally intensive, you can consider C development

Thread Creation

Creation of Threads:

1. Call directly, threading. Thread (target=sayhi,args= (1,)

2. Inherited invocation:

Call directly:

Import Timeimport threadingbegin=time.time () def bar (n):    print (' bar%s '%n)    Time.sleep (3) def foo (n):    Print (' foo%s '%n)    time.sleep (2) T1 = Threading. Thread (Target=bar, args= (1,)) # creates T1 thread object t2 = Threading. Thread (Target=foo, args= (2,)) # Creates a T2 thread object T1.start ()   # thread starts, starts to preempt CPU resources t2.start ()   # thread starts, starts to preempt CPU resources end=time.time () T1.join ()   # thread blocked, executes the main thread after the day T1 T2.join ()   

An inherited invocation:

Import Threadingimport Timeclass MyThread (threading. Thread):    def __init__ (self, num):        threading. Thread.__init__ (self)        self.num = num    def run (self):  # defines the function to run for each thread        print ("Running on number:%s"% Self.num)        Time.sleep (3) if __name__ = = ' __main__ ':    t1 = MyThread (1)    t2 = MyThread (2)    T1.start ()    T2.start ()
Thread Common methods

Thread.Join (): The parent thread of this child thread will remain blocked until the child thread finishes running.

Import threadingfrom time import Ctime,sleepimport timedef Music (func): For I in range (2): Print ("Begin Listeni Ng to%s.%s "% (Func,ctime ())] Sleep (4) print (" End Listening%s "%ctime ()) def Move (func): For I in range (2 ): Print ("Begin watching at the%s! %s "% (Func,ctime ())) sleep (5) print (' End watching%s '%ctime ()) threads = []T1 = Threading. Thread (target=music,args= (' Li Qi Xiang ',)) threads.append (t1) t2 = Threading.            Thread (target=move,args= (' Forrest Gump ')) Threads.append (t2) If __name__ = = ' __main__ ': for T in Threads:t.start () # T1.start (). T2.start () # t.join () # Serial execution, T1.start () after entering T1.join () wait until T1 executes in T2 # t.join () # python default Take the last for loop of the T2, equivalent to T2.join () # T1.join () # The main thread of print () will appear in the 8th second, and finally print end movies T.join () # t2 . Join (), T2 executes end after the program finishes print ("All over%s"%ctime ())

Setdemaon (True):

The

declares a thread as a daemon thread and must be set before the start () method call, if it is not set to a daemon, it will be indefinitely suspended. This method is basically the opposite of join. When we are running the program, executing a main thread, if the main thread creates a sub-thread, the main thread and the child thread are suited two ways, running separately, then when the main thread finishes trying to exit, it verifies that the child thread is complete. If the child thread is not completed, the main thread waits for the child thread to complete before exiting. But sometimes what we need is that as soon as the main thread is complete, regardless of whether the child thread is complete or not, it exits with the main thread, so you can use Setdaemon (True)

Import threadingfrom time import Ctime,sleepimport timedef Music (func): For    I in range (2):        print ("Begin listenin G to%s.%s "% (Func,ctime ())]        sleep (4)        print (" End Listening%s "%ctime ()) def Move (func): For    I in range (2): C5/>print ("Begin watching at the%s! %s "% (Func,ctime ()))        Sleep (5)        print (' End watching%s '%ctime ()) threads = []T1 = Threading. Thread (target=music,args= (' Li Qi Xiang ',)) threads.append (t1) t2 = Threading. Thread (target=move,args= (' Forrest Gump ')) Threads.append (t2) If __name__ = = ' __main__ ':    # T2.setdaemon (True)    # Ends the program after executing T1, i.e. does not execute print (' End watching%s '%ctime ())     for T in Threads:        T.setdaemon (True)    # declares a thread as a daemon thread, You must set        T.start ()            # T1.start (). T2.start () print ("All over    %s"%ctime ()) before the start () method call

Thread-provided methods
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 threading 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's Gil ( Global Interpreter Lock )

Interpreter reason: Due to the reason of CPython interpretation, only one thread can be invoked at the same time, it is understandable that Python does not have multiple threads

CPython implementation Details: In CPython, because the global interpreter is locked, only one thread can execute Python code at a time (even if some performance-oriented libraries might overcome this limitation). If you want your application to make better use of compute resources for multicore computers, we recommend that you use multi-processing. However, if you want to run multiple I/O intensive tasks at the same time, the thread is still a suitable model.

Python Learning---threading learning 1220

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.