Python threading learning notes

Source: Internet
Author: User

1. Use of the join () method

Join method. If a thread or function needs to call another thread during execution and can be executed only after it is completed, the join method of the called thread can be used when this thread is called.

 

Example:

Import threading, time

Class mythread (threading. Thread ):
Def _ init _ (self, ID ):
Threading. thread. _ init _ (Self)
Self. ID = ID

Def run (Self ):
Time. Sleep (5)
Print self. ID

T = mythread (1)
Def func ():
T. Start ()
# T. Join ()
Print T. isalive ()

Print func ()
Output result

True (thread running)

None

Then wait 5 seconds and then output 1

 

If the # T. Join well number is removed

Output 1

False (thread exits)

None

 

 

2. Set the thread name

Import threading

Class mythread (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)

Def run (Self ):
Print self. getname ()

T1 = mythread ('t1 ')
Print t1.getname ()
Print ID (T1)

T2 = mythread ('t2 ')
T2.start () # note the following:
T2.getname ()
T2.setname ('TT ')
T2.getname ()
Print ID (T2)

 

 

3. Daemon

Setdaemon ()

This method is basically the opposite of join. When we are running the program, we will execute a main thread. If the main thread creates another sub-thread, and the main thread and sub-thread run separately, when the main thread completes and wants to exit, checks whether the Sub-thread is complete. If the sub-thread is not completed, the main thread will wait for the sub-thread to complete and then exit. But sometimes we need to exit with the main thread as long as the main thread is completed and the thread is not completed, the setdaemon method can be used.

 

The procedure is as follows:

The following example shows how to set the sub-thread to end with the end of the main thread:

Import threading

Import time

 

Class mythread (threading. Thread ):

Def _ init _ (self, threadname ):

Threading. thread. _ init _ (self, name = threadname)

Def run (Self ):

Time. Sleep (5)

 

Print self. getname ()

 

Def fun1 ():

T1.start ()

Print 'fun1 done'

 

Def fun2 ():

T2.start ()

Print 'fun2 done'

 

T1 = mythread ('t1 ')

T2 = mythread ('t2 ')

T2.setdaemon (true)

Fun1 ()

Fun2 ()

 

 

In the preceding example, we assume that:
Fun1 done

Fun2 done

T1

But in the interaction mode, the main thread is terminated only when Python exits, so the result T2.

 

4. Thread Creation Method

If you want to create a thread object, it is very simple, as long as your class inherits threading. thread, and then in _ init _, You can first call the _ init _ method of threading. Thread:
This is just an empty thread. I don't want him to pull the empty car. He has to do some real work for me. It's easy to rewrite the run () method of the class and put all the things you want to do during thread execution into it.
The above Code allows this thread to output information to the screen every second after execution. After 10 times, the getname () is threading. A Method of the thread class to obtain the name of the thread object. Another method, setname (), is to set the name of the thread object.

To create a thread, you must first create a thread object.
Mythread1 = mythread ('mythread 1 ')
After a thread object is created, it is in the "Born" state. How can this thread object start to run? You only need to call the START () method of the thread object:
Mythread1.start ()
Now the thread is in the "ready" or "runnable" state.
Strange? Isn't it already started? Why is it not called the "running" status? There is actually a reason. Because our computers generally do not have real parallel processing capabilities. The so-called multithreading only divides the time into segments, and then allows a thread to execute each time period, then enters the "sleeping" state, and then wakes up another thread in the "sleeping" state, so loop runnable-> sleeping-> runnable ..., it's just because the computer runs fast and the interval between time segments is very small. We don't feel it. We thought it was done at the same time. Therefore, after a thread starts, it is only in a running state. When will it be scheduled by the system.
When will a thread "dead? Generally, when the run method of the thread object ends or an exception is thrown during execution, the thread ends. The system automatically clears the "dead" status thread.
Program:

Import threading
Import time

Class mythread (threading. Thread ):
Def _ init _ (self, threadname ):
Threading. thread. _ init _ (self, name = threadname)

Def run (Self ):
For I in range (10 ):
Print self. getname (), I
Time. Sleep (1)

T1 = mythread ('t1 ')
T1.start ()

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.