Python Learning Notes-threads (1)

Source: Internet
Author: User

This is the first Python multi-threaded learning note to see what is multi-threading and how to create him.


In the script that Python wrote before, all we used was single-process one-thread operation.

For example

Traditional single-process, single-threaded program

Import Timedef F1 (ARG,): Time.sleep (5) print (ARG) for I in range: F1 (i)


However, many times, we need concurrent processing of multiple tasks, for example, a playback software in the movie, he needs to play the graphics, sound, subtitles, this time he created a process of playing software, and then the internal running a number of threads (the first thread is called the main path), One of the lines Cheng the image, one put sound, one subtitle, etc. As you can see from this example, a process can also include multiple threads.


So, if we need to implement multiple task processing, we can use:

    1. Multi-process

    2. Multithreading

    3. Multi-process + multithreading


In Python, he has a special rule that each process can have only one thread Chengyang CPU execution at a time, while in C#,java, any thread, even multiple threads in the same process, can be executed concurrently. As a result, Python is suitable for multi-process processing when dealing with computationally intensive operations (large amounts of CPU execution), since more threads are not executed concurrently in the same process, while IO-intensive operations (such as accessing the network, file operations), because he does not consume CPU resources, Most of the time is spent on IO operations waiting, so more suitable for multi-threaded processing.


Let's look at a few simple examples below.


Example 1:

A few points

    1. Threading.current_thread () is the instance that gets the current thread, and the name of the main path is called Mainthread

    2. T.start () means that the thread is started, but he does not necessarily execute it immediately, so we can see that the thread Mainthread completed before executing the child thread Thread-1

#!/usr/bin/env python#-*-coding:utf-8-*-# author:alex liimport timedef F1 (ARG, t=none): Time.sleep (5) Print (Threa Ding.current_thread (). name,arg) Import Threadingt = Threading. Thread (TARGET=F1, args= (1,)) T.start () # does not mean that the current thread will be executed immediately print (Threading.current_thread (). Name)--------------- MainThreadThread-1 1


Example 2:

If we add a Setdaemon (True) statement based on the above, then the entire program ends immediately after the main thread ends and does not wait for the child thread to execute

#!/usr/bin/env python#-*-coding:utf-8-*-# author:alex liimport timedef F1 (ARG, t=none): Time.sleep (5) Print (Threa Ding.current_thread (). name,arg) Import Threadingt = Threading. Thread (TARGET=F1, args= (1,)) T.setdaemon (True) T.start () # does not represent that the current thread will be executed immediately with print (Threading.current_thread (). Name)----- ----------Mainthread


Example 3, if we use T.join () on the basis of Example 1, then you can specify the main thread to this place, just wait for me, you can set the waiting time, such as T.join (2) is waiting for 2 seconds, if nothing is set, the main thread will wait until the end of the child thread to execute


Like what

#!/usr/bin/env python#-*-coding:utf-8-*-# author:alex liimport timedef F1 (ARG, t=none): Time.sleep (5) Print (Threa Ding.current_thread (). name,arg) Import Threadingt = Threading. Thread (TARGET=F1, args= (1,)) T.start () # does not represent that the current thread will be executed immediately t.join () #主进程在这给我挂起print (Threading.current_thread (). Name)---- -----------Thread-1 1MainThread



Looking at these 3 examples, it can be found that creating multithreading is very simple, importing modules directly, and then invoking the thread () class instance of the module as an object. If we look at the source code, we will find that our incoming functions and ganso are encapsulated in the constructor, and when we call the start () method, he automatically calls Bootstrap ()->bootstrap_inner ()->run () and finally the run () Inside executes our own function and passes in the parameter


    def run (self):         "" "Method  Representing the thread ' S activity.        you may  override this method in a subclass. the standard run ()   Method        invokes the callable object passed  to the object ' s constructor as the         target argument, if any, with sequential and keyword arguments  taken        from the args and kwargs  arguments, respectively.         "" "         try:            if self._ Target:   &nbSp;            self._target (*self._args, ** Self._kwargs)         finally:             # avoid a refcycle if the thread is  running a function with             # an argument that has a member that points to the  thread.            del self._target,  self._args, self._kwargs


Once you know the logic of his work, here's a look at another way to create it. We can customize the class to inherit the Threading.thread, write a constructor, and then instantiate the parameters directly from their own package, and then execute super, so that Thread will perform the above analysis, when he executes to run (), Because at the bottom we define a run (), then he will not execute the one above but execute our own.


As you can see, the effect of multithreading is the same, but we can add more new features to go in ~


Python 3.5.2 (V3.5.2:4DEF2A2901A5, June, 22:18:55) [MSC v.1900-bit (AMD64)] on win32>>> import Threadin Gclass MyThread (Threading. Thread): Def __init__ (self, func,args): Self.func = func Self.args = args Super (MyThread, self). __init__ ( ) def run (self): Self.func (Self.args) def F2 (ARG): print (arg) obj = MyThread (f2,123) Obj.start () 123


This article is from the "Mapo Tofu" blog, please be sure to keep this source http://beanxyz.blog.51cto.com/5570417/1865736

Python Learning Notes-threads (1)

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.