Python concurrent Programming: Multithreading-thread other properties and methods of objects

Source: Internet
Author: User

Other properties or methods of the thread object

Introduced:

Thread instance object Method    # isAlive (): Returns the thread is active    # getName (): Returns the thread name    # setnmae (): Sets the thread name threading module provides some methods:    # Threading.currentthread ():    returns the current thread variable    # threading.enumerate ():    Returns a list containing 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 ())

  

Verify

From threading import threadimport threadingfrom multiprocessing import processimport osimport timedef work ():    Time.sleep (3)    print (Threading.current_thread (). GetName ()) If __name__ = = ' __main__ ':    # Open thread under main process    T = Thread (target=work)    t.start ()    print (Threading.current_thread (). GetName ())    print (Threading.current_ Thread ())   # main thread    print (Threading.enumerate ())    # with two running threads in the main thread    print (Threading.active_count ())    print (' main thread/main process ')

Execution results

Mainthread<_mainthread (Mainthread, started 140037784917824) >[<_mainthread (Mainthread, started 140037784917824), <thread (Thread-1, started 140037751482112) >]2 main thread/main process Thread-1

The main thread waits for the child thread to end

Import timedef Sayhi (name):    time.sleep (2)    print ('%s say hello '% name) if __name__ = = ' __main__ ':    t = Thread (t Arget=sayhi, args= (' Mike ',))    T.start ()    t.join ()    print (' main thread ')    print (t.is_alive ())

Execution results

Mike say hello Main thread false

  

Python concurrent Programming: Multithreading-thread other properties and methods of objects

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.