Python Basics-Nineth-9.2 Threads and multithreading

Source: Internet
Author: User

Single Thread
Import timebegintime = Time.time () for a in range:    print (a)    time.sleep (1) Shijian = Time.time ()- Begintimeprint (Shijian)  #10.000571966171265

We can see that the above code is pure single-threaded, a way to go black, pay attention to successively, so spent more than 10 seconds

Multithreading

After all, waiting is annoying, what method can not so time ah, Ah, the protagonist debut, welcome multi-threading, that multithreading did a thing? It can do many things at the same time, take the example above, when the thread sleeps, it will go to execute other threads.

Import Threadingimport timedef Printnum (a):    time.sleep (1)    print (a) BeginTime = Time.time () for I in Range (10):    t = Threading. Thread (target=printnum,args= (i,))    T.start () # for I in range: #     t.join () Shijian = Time.time ()- Begintimeprint (Shijian) Results:    0.0010001659393310547    2    1    0    4    6    9    3    5    7    8

See this, you may think, the output of the result is disorderly, because multithreading is each thread to execute their own, so there may be a preemption of the output resources.

You may also think, how just 0.001 seconds to complete, too illogical, then I tell you, this time is the main thread of execution time, if you want to know all the thread execution time, as long as the interpretation of the T.join () These two lines of code, the result is generally 1 seconds more points.

Detailed process
#引入线程模块threadingimport threadingimport time# defines the execution method in the thread Def Printnum (a):    print (' num: ', a)    Time.sleep (1) def Printstr (STR1,STR2):    print (str1, ': ', str2)    time.sleep (1) #初始化一个线程对象t_0 = Threading. Thread (target=printnum,args= (888)) #启动线程t_0. Start () #target指定需要执行的函数名, args specifies the parameter t_1 in the form of a tuple = threading. Thread (target=printstr,args= (' The ' The Arg ', ' string ')) T_1.start () #一次创建10个线程对象并启动for i in range:    t = Threading. Thread (target=printnum,args= (i,))    T.start ()

Threading Module Detailed

There is no priority, thread group, or stop, pause, resume, or interrupt in a Python thread, and the thread can only be destroyed as the code in the thread finishes executing.

  Classes provided by the threading module

-- Thread, Lock, Rlock, Condition, [Bounded]semaphore, Event, Timer, local

common methods in the threading module
    1. Threading.currentthread () returns the current thread variable
    2. Threading.enumerate () Returns a list that contains a running thread, running after the thread has started and ends, excluding pre-and post-termination threads
    3. Threading.activecount () returns the number of running threads with the same result as Len (Threading.enumerate ())

advanced usage of join

Import Timeimport threadingdef Printnum (a):    print (' num: ', a)    Time.sleep (1) def threadtest ():    return Threading. Thread (target=printnum,args= (999,)) Thread_li = []for i in range]:    t = threadtest ()    thread_li.append (t) for t In Thread_li:    T.start () for T in Thread_li:    t.join () print (' finished ')

We can see from the above code that the Join method is no longer the same as before the thread is queued to execute, all the threads execute after the end of the main thread to execute the final code!

Lock class and Rloc class

Lock resources, let threads operate one by one

    • Acquire to Thread lock
    • Release To line Threads unlocked
Import Threadinglock = Threading. Lock ()  #创建锁对象lock. Acquire () Lock.acquire () #生成死锁, blocking lock.release () lock.release ()

Lock locking and unlocking two methods can only appear one after the other, otherwise it is easy to deadlock

Import Threadingrlock = Threading. Rlock ()  #创建锁对象Rlock. Acquire () Rlock.acquire () #没有阻塞Rlock. Release () Rlock.release ()

And Rlock is more casual, as long as the lock and unlock two ways to double appear on it.

For more detailed information, see: http://www.cnblogs.com/xinsiwei18/p/5697802.html

You are welcome to ask questions and questions about my blog content! Thanks

Author: Pat Province Mr.

Python Basics-Nineth-9.2 threads and multithreading

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.