Python-based multi-threading

Source: Internet
Author: User

Concept

Process : A process is a dynamic execution process of a program on a data set

Program: Code

Datasets: Resources needed during program execution

Process Control BLOCK: a unit that completes a State save

Threads: threads are pinned on the process, in order to improve the concurrency of the system

Thread is the entity of the process

A process is a resource management unit, the thread is the smallest execution unit

The relationship between threads and processes

(1) A thread can belong to only one process, while a process may have multiple threads, but at least one thread.
(2) A resource is allocated to a process, and all the threads of the same process share all the resources of that process.
(3) The CPU is assigned to a thread, that is, a thread that actually runs on the CPU.

process/Thread switching principle: switching operator, operating system

1, time slices, the processing time of the task

2, encountered IO operation, switch

For example, the socket sends a system call, and then waits for the operating system to be called and the operating system listens

3. Priority switching

Concurrency: The ability to execute multiple programs in a single time period

Toggle: The task State of the Save, state recovery, is the concurrency condition

Note: In order to share a data set, thread switching costs much less than the cost of process switching

Parallel: multiple CPUs, capable of executing multiple programs at the same time

Synchronization: Synchronization refers to a process that executes a request, and if the request takes a while to return information, the process waits until the return message is received.

Async: Async refers to a process that does not have to wait, but continues to do the following, regardless of the state of other processes. The system notifies the process when a message is returned, which can improve the efficiency of execution.

For example, the telephone is synchronous communication, the short interest is asynchronous communication.

The Python thread

Python locking: At the same time only one thread comes out and executes in a real thread parallel under a process, wasting the benefits of multicore (in the back)

Threading Module

The thread class is created directly

1 Import Threading 2 Import time 3  4 def countnum (n): # defines a function for a thread to run 5  6     print ("Running on number:%s"%n) 7
   8     Time.sleep (3) 9 if __name__ = = ' __main__ ': one by one     T1 = threading. Thread (target=countnum,args= ()) #生成一个线程实例13     t2 = Threading. Thread (target=countnum,args=,))     T1.start () #启动线程16     t2.start ()     print ("ending!")

Thread Class inheritance Creation
#继承Thread式创建import threadingimport timeclass MyThread (threading. Thread):    def __init__ (self,num):        Threading. Thread.__init__ (self)        self.num=num    def run (self):        print ("Running on number:%s"%self.num)        Time.sleep (3) t1=mythread (T2=mythread) T1.start () T2.start () print ("Ending")
Join () and Setdaemon ()
# join (): The parent thread of this child thread will remain blocked until the child thread finishes running.         # Setdaemon (True): ' The thread is declared as a daemon thread and must be set before the start () method call, and if not set to the daemon, it will be indefinitely suspended. 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 long as the main thread is complete, regardless of whether the child thread is complete, and the main thread to exit, then you can use the Setdaemon method "" "Import threadingfrom time import Ctime,sleepimport Timedef Music (name): Print ("Begin listening to {name}". {time} '. Format (Name=name,time=ctime ())) sleep (3) print ("End Listening {time}". Format (Time=ctime ())) def Blog ( Title): Print ("Begin recording the {title}".  {time} '. Format (Title=title,time=ctime ())) sleep (5) print (' End recording {time} '. Format (Time=ctime ())) threads = []T1 = Threading. Thread (target=music,args= (' FILL ME ',)) t2 = Threading. Thread (target=blog,args= (",)) threads.append (T1) threads.append (t2) If __name__ = = ' __main__ ': #t2. Setdaemon (True) fo      R T in Threads: #t. Setdaemon (True) #注意: Be sure to set T.start before start ()  #t. Join () #t1. Join () #t2. Join () # Consider the results under these three join locations? Print ("All over%s"%ctime ())
Daemona Boolean value indicating whether this thread was a daemon thread (True) or not (False). This must was set before start () is called and otherwise runtimeerror is raised. Its initial value was inherited from the creating thread; The main thread is a daemon thread and therefore all threads created in the main thread default to daemon = False.the Entire Python program exits when no alive Non-daemon threads is Left. When daemon is set to true, if the main thread exits, the child threads will also exit, and the child threads will continue to run until they exit normally.
Other methods

Thread instance object's method  # isAlive (): Returns whether the thread is active.  # getName (): Returns the thread name.  # SetName (): Sets the thread name. Some of the methods provided by the threading module are:  # 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 ()).

IO-intensive tasks: There are a lot of IO operations in the program

Compute-intensive tasks: There are a number of computational operations in the program

For Python, processing IO-intensive tasks has the advantage of not having the advantage of computationally intensive tasks

Python-based multi-threading

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.