Python multi-thread threading module

Source: Internet
Author: User
Tags mutex semaphore

Threading objects in the module

    • In addition to the thread object, there are many synchronization-related objects
    • Threading module supports the daemon thread mechanism
Thread Object

Direct Call method
Import threadingimport time def sayhi (num): #定义每个线程要运行的函数     Print ("Running on number:%s"%num)     Time.sleep (3) if __ name__ = = ' __main__ ':     t1 = Threading. Thread (target=sayhi,args= (1,)) #生成一个线程实例    t2 = Threading. Thread (target=sayhi,args= (2,)) #生成另一个线程实例     T1.start () #启动线程    t2.start () #启动另一个线程     print (T1.getname ()) # Get Thread name    print (T2.getname ())
Inheriting class mode
Import Threadingimport Time  class MyThread (threading. Thread):    def __init__ (self,num):        Threading. Thread.__init__ (self)        self.num = num     def run (self): #定义每个线程要运行的函数         Print ("Running on number:%s"%self.num)         Time.sleep (3) if __name__ = = ' __main__ ':     t1 = MyThread (1)    t2 = MyThread (2)    T1.start ()    T2.start ()

Note: When you start this thread, you only call the Run method of the class, so when you define the subclass, be sure to go back to the parent class's Run method, or the thread will not do anything after it is started.

Join and Daemon Issues
    • Join: In order for the main thread to wait for the child thread to end.
    • Daemon: When a thread is set as a daemon thread, the thread becomes the "servant" of the thread that sets it as the daemon thread, and when its "owner" exits, it will follow the "owner's exit" regardless of whether his or her task is completed.

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These was only useful when the main program was running, and it's okay to kill them off once the other, Non-daemon, threads Have exited.

Without daemon threads, you ' d has to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon thr EADS is killed automatically.

#_ *_coding:utf-8_*___author__ = ' Alex Li ' import timeimport threading  def run (n):     print (' [%s]------ Running----\ n '% n)    time.sleep (2)    print ('--done--') def Main (): For    I in range (5):        t = Threading. Thread (Target=run,args=[i,])        T.start ()        t.join (1)        print (' Starting thread ', T.getname ())  m = Threading. Thread (target=main,args=[]) M.setdaemon (True) #将main线程设置为Daemon线程, which is the daemon thread of the main thread of the program, and when the main thread exits, M threads exit, and other sub-threads initiated by M will exit at the same time. Whether or not the task M.start () m.join (timeout=2) print ("---main thread done----")
Lock object (thread lock-- Mutex Mutex) The difference between the thread lock and the Gil

Many people do not understand that Python already has a Gil, how to engage a thread lock. Give a picture first:

The first thing to make clear is that the thread lock is a user-level locking mechanism that has nothing to do with the interpreter's Gil, nor does it have anything to do with each other. Next, we should pay attention to the Gil description, it said that "there will be only one thread on the CPU at the same time", this does not mean that the CPU-consuming thread after the end of the line to execute another thread (if so, there is no multi-threaded argument), then the thread is likely to perform the task, Being interrupted, let out the CPU (Python's threading mechanism is called by the thread interface of C, which is called by the native thread, so the scheduling scheme is determined by the operating system).

That is, it goes back to the thread created in Python. , the red thread's task is to do a "plus 1" operation, because this "plus one" operation is not "atomic operation", so, when executed, it is likely to be interrupted. If the thread that interrupts red at this point is a blue thread and it is also using count (shared resources), then because the red process does not complete its task, the blue process reads the same value as the red process reads (that is, count=0). At this point, the blue thread executes normally, completes the "plus 1" task (count=1), and then the red process resumes execution, but now it gets the "count=0" and then completes the "plus 1" task, which is then "Count=1".

In retrospect, the result we wanted at first was "count=2", not "count=1". In this process, we adhere to the Gil rules, but it is likely that the above phenomenon, this is what I said, the thread lock is a user-level locks, not related to the Gil, I have to consider whether the business logic needs to do "atomic operation" problem, if necessary, it requires the thread lock mechanism.

Basic Use Method
Import Timeimport Threading Def addnum ():    global num #在每个线程中都获取这个全局变量    print ('--get num: ', num)    time.sleep ( 1)    Lock.acquire () #修改数据前加锁    num  -=1 #对此公共变量进行-1 Operation    lock.release () #修改后释放 num =  #设定一个共享变量thread _list = []lock = Threading. Lock () #生成全局锁for i in range:    t = Threading. Thread (Target=addnum)    T.start ()    thread_list.append (t) for T in Thread_list: #等待所有线程执行完毕    t.join () print (' Final num: ', num)
Rlock (Recursive Lock)

It's a mechanism to add a lock again in a big lock.

Basic Use Method
Import Threading,time def run1 ():    print ("Grab the first part data")    Lock.acquire ()    global num    num +=1< C4/>lock.release ()    return numdef run2 ():    print ("Grab the second part data")    Lock.acquire ()    Global  num2    num2+=1    lock.release ()    return num2def run3 ():    lock.acquire ()    res = RUN1 ()    Print ('--------between run1 and run2-----')    res2 = run2 ()    lock.release ()    print (res,res2)  if __ name__ = = ' __main__ ':     num,num2 = 0,0    lock = Threading. Rlock () for    I in range:        t = Threading. Thread (TARGET=RUN3)        T.start () while Threading.active_count ()! = 1:    print (Threading.active_count ()) Else:    print ('----All threads do---')    print (num,num2)
Semaphore Object (Semaphore)

mutexes allow only one thread to change data at the same time, while Semaphore allows a certain number of threads to change data, such as a toilet with 3 pits, which allows up to 3 people to go to the toilet, while the latter can only wait for someone to come out.

Import Threading,time def run (n):    semaphore.acquire ()    time.sleep (1)    print ("Run the Thread:%s\n"%n)    Semaphore.release () if __name__ = = ' __main__ ':     num= 0    semaphore  = Threading. Boundedsemaphore (5) #最多允许5个线程同时运行 for    i in range:        t = Threading. Thread (target=run,args= (i,))        T.start () while Threading.active_count ()! = 1:    pass #print threading.active_ Count () Else: print (    '----all threads-Done---')    print (num)
Timer Object

This is class represents an action that should is run only after a certain amount of time have passed

Timers is started, as with the threads, by calling their start() method. The timer can be stopped (before its action have begun) by calling the cancel() method. The interval the timer would wait before executing its action is not being exactly the same as the interval specified by the User.

def hello ():    print ("Hello, world") T = Timer (30.0, Hello) t.start ()  # After the seconds, "Hello, World" would be prin Ted
Events Object

An event was a simple synchronization object;

The event represents an internal flag, and threads
Can wait for the flag to be set, or set or clear the flag themselves.

event = Threading. Event ()

# A client thread can wait for the flag to be set
Event.wait ()

# A server thread can set or reset it
Event.set ()
Event.clear ()
IF the flag is set, the wait method doesn ' t does anything.
IF the flag is cleared, wait would block until it becomes set again.
Any number of threads could wait for the same event.

Through the event to realize the interaction between two or more threads, here is an example of a traffic light, that is, start a thread to do traffic lights, generate a few threads to do the vehicle, the vehicle driving by red light stop, Green Line rules.

Import Threading,timeimport Randomdef Light (): If not Event.isset (): Event.set () #wait就不阻塞 #绿灯状态 count = 0            While True:if count < 10:print (' \033[42;1m--green light on---\033[0m ') elif count <13:                Print (' \033[43;1m--yellow light on---\033[0m ') elif count <20:if event.isset (): Event.clear () print (' \033[41;1m--red light on---\033[0m ') else:count = 0 Eve        Nt.set () #打开绿灯 time.sleep (1) Count +=1def car (n): While 1:time.sleep (Random.randrange (10)) If Event.isset (): #绿灯 print ("car [%s] is running:"% n) else:print ("car [%s] is waiting f Or the red light: "%n) if __name__ = = ' __main__ ', event = threading. Event () Light = threading. Thread (Target=light) Light.start () for I in Range (3): T = Threading. Thread (target=car,args= (i,)) T.start ()

Python multi-thread threading module

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.