Python multithreaded Programming (III): Important functions and methods of Threading.thread classes _python

Source: Internet
Author: User

This article mainly introduces some of the main methods of main class thread in the threading module, the example code is as follows:

Copy Code code as follows:

'''
Created on 2012-9-7

@author: walfred
@module: Thread. ThreadTest3
@description:
'''
Import threading

Class Mythread (threading. Thread):
def __init__ (self):
Threading. Thread.__init__ (self)

def run (self):
Print "I am%s"% (Self.name)

if __name__ = = "__main__":
For I in range (0, 5):
My_thread = Mythread ()
My_thread.start ()

Name-related

You can specify name for each thread, and the default is Thread-no form, as the example code above prints:

Copy Code code as follows:

I am Thread-1
I am Thread-2
I am Thread-3
I am Thread-4
I am THREAD-5

Of course you can specify the name of each thread, which is through the SetName method, code:

Copy Code code as follows:

def __init__ (self):
Threading. Thread.__init__ (self)
Self.setname ("new" + Self.name)

Join Method

The Join method prototype is used to block the current context until the thread is run:

Copy Code code as follows:

def join (self, timeout=none):
Timeout can set timeout
Timeout can set timeout to nibble

Setdaemon method

When we execute a main thread in the program, if the main thread creates a child thread, the main thread and the child threads are suited two ways, and when the main thread completes to exit, it verifies that the child thread is complete. If the child thread does not complete, the main thread waits for the child thread to complete and then exits. But sometimes what we need is, as long as the main thread completes, regardless of whether the child thread is completed, and the main thread exits together, you can use the Setdaemon method and set its argument to true.

Of course, the above list is only one of the methods that we often use in programming, more methods, see: Higher-level threading interface

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.