Threads in Python

Source: Internet
Author: User
Tags thread class

1. Creation of Threads 1.1 through threadClass is created directly
    import threading    import time        def foo(n):        time.sleep(n)        print("foo func:",n)        def bar(n):        time.sleep(n)        print("bar func:",n)        s1=time.time()        #创建一个线程实例t1,foo为这个线程要运行的函数    t1=threading.Thread(target=foo,args=(3,))    t1.start()    #启动线程t1        #创建一个线程实例t2,bar为这个线程要运行的函数    t2=threading.Thread(target=bar,args=(5,))    t2.start()    #启动线程t2        print("ending")        s2=time.time()        print("cost time:",s2-s1)

In this program, a function sleeps for a few seconds before printing a word, and the second function sleeps for a few seconds before printing a word.

The program then instantiates two threads and calls two functions to execute, and the final print program asks how much time has been executed in total

The results of the program run as follows:

endingcost time: 0.002000093460083008foo func: 3bar func: 5

The program runs the parent thread, prints "ending" , and then prints the time that the program executes the parent thread before it runs the child thread

1.2 By threadClass to inherit the creation of an
    import threading    import time        # 定义MyThread类,其继承自threading.Thread这个父类    class MyThread(threading.Thread):             def __init__(self):            threading.Thread.__init__(self)            def run(self):            print("ok")            time.sleep(2)            print("end t1")        # 对类进行实例化    t1=MyThread()        # 启动线程    t1.start()    print("ending")
2. Some common methods of the thread class 2.1 join(): The main thread will be blocked until the child thread is complete * * *
线程的join方法必须在子线程的start方法之后定义

In the first example, add two lines of code, as follows:

    import threading    import time            def foo(n):        time.sleep(n)        print("foo func:",n)        def bar(n):        time.sleep(n)        print("bar func:",n)        s1=time.time()    t1=threading.Thread(target=foo,args=(3,))    t1.start()        t2=threading.Thread(target=bar,args=(5,))    t2.start()        t1.join()       # 阻塞t1线程    t2.join()       # 阻塞t2线程        print("ending")    s2=time.time()        print("cost time:",s2-s1)

Execute the program again and run the following results:

foo func: 3bar func: 5endingcost time: 5.002285957336426

When the program runs to the Foo method in child thread T1, it sleeps for 3 seconds, while the child thread T2 is sleeping

When the child thread T1 sleep is complete, the print statement in the Foo function begins printing, and then the child thread T1 execution completes

After 2 seconds, the child thread T2 Sleep completes, starts printing the print statement in the bar function, and then the child thread T2 also executes the completion.

Until then, the main thread has been in a blocking state. The main thread will not execute until the child threads have finished executing

2.2 Setdeamon (True)
setDaemon方法作用是将进程声明为守护线程,必须在`start()`方法调用之前,

If not set as the daemon thread, the program will be suspended indefinitely

During the execution of a program, the main thread and the child line routines run separately when the main thread creates a child thread.

When the main thread finishes running, it verifies that the child thread is finished, and if the child thread executes, the main thread waits for the child thread to complete before exiting.

However, there are times when the main thread executes, and it exits with the main thread, regardless of whether or not the child thread is finished, this calls the setDeamon method.

Take the first example, and now I want the T1 and T2 of the child threads to close with the main thread, the code is as follows:

    import threading    import time        def foo(n):        print("foo start")        time.sleep(n)        print("foo end...")        def bar(n):        print("bar start")        time.sleep(n)        print("bar end...")        s1 = time.time()    t1 = threading.Thread(target=foo, args=(3,))    t1.setDaemon(True)    t1.start()        t2 = threading.Thread(target=bar, args=(5,))    t2.setDaemon(True)    t2.start()        print("ending")    s2 = time.time()        print("cost time:", s2 - s1)

The results of the program run as follows:

foo startbar startendingcost time: 0.003000020980834961

As you can see, after the T1 and T2 are declared as daemon threads, the program executes from top to bottom, executes the Foo method in the child thread T1, prints the first print statement in the Foo function, and then the child thread T1 into the sleep state.

Then the child thread T2 executes, prints the first print statement in the bar function, and then the child thread T2 into sleep, the program switches to the main thread to run

The main thread finishes printing the "ending" statement, discovering that the child threads T1 and T2 have been set as daemons, so the main thread does not need to wait for two sub-threads to complete, but ends immediately, printing the entire execution time of the program.

The entire program is closed along with the main thread.

2.3 Sub-Threading some other methods
isAlive()           #判断一个线程是否是活动线程getName()           #返回线程的名字setName()           #设置线程的名字
    import threading    import time        def foo(n):        time.sleep(n)        print("foo func:", n)        def bar(n):        time.sleep(n)        print("bar func:", n)        s1 = time.time()    t1 = threading.Thread(target=foo, args=(3,))    t1.setDaemon(True)        print("线程还未启动时,判断t1是否是活动的线程:", t1.isAlive())  # 线程还未启动,所以是False    t1.start()  # 启动线程    print("线程已启动时,判断t1是否是活动的线程:", t1.isAlive())  # 线程已启动,所以是True    print("修改前的线程名为:",t1.getName())  # 获取线程名    t1.setName("t1")        #设置线程名    print("修改后的线程名为:",t1.getName())  # 获取线程名        t1.join()        print("线程执行完成时,判断t1是不否是活动的线程:", t1.isAlive())  # 线程已执行完成,所以是False        # print(threading.activeCount())    print("ending")    s2 = time.time()        print("cost time:", s2 - s1)

Program execution Results:

线程还未启动时,判断t1是否是活动的线程: False线程已启动时,判断t1是否是活动的线程: True修改前的线程名为: Thread-1修改后的线程名为: t1foo func: 3线程执行完成时,判断t1是不否是活动的线程: Falseendingcost time: 3.001171588897705
Some of the methods provided by the 3.threading module
threading.currentThread()   #返回当前的线程变量threading.enumerate()       #返回一个包含正在运行的线程的列表,不包括启动前和终止后的线程threading.activeCount()     #返回正在运行的线程数量,等同于len(threading.enumerate())
    import threading    import time    def foo(n):        time.sleep(n)        print("foo func:", n)    def bar(n):        time.sleep(n)        print("bar func:", n)    s1 = time.time()    t1 = threading.Thread(target=foo, args=(3,))    t1.setDaemon(True)    t1.start()    t2 = threading.Thread(target=bar, args=(5,))    t2.setDaemon(True)    t2.start()    print("程序中正在运行的线程数量:",threading.activeCount())    print("程序中当前的线程变量:",threading.currentThread())    print("当前正在运行的线程的列表:",threading.enumerate())    print("ending")    s2 = time.time()    print("cost time:", s2 - s1)

Program execution Results:

程序中正在运行的线程数量: 3程序中当前的线程变量: <_MainThread(MainThread, started 7064)>当前正在运行的线程的列表: [<_MainThread(MainThread, started 7064)>, <Thread(Thread-1, started daemon 6384)>, <Thread(Thread-2, started daemon 2640)>]endingcost time: 0.002000093460083008

Threads in Python

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.