Python learning Experience (vii) in-depth understanding of threading multithreaded Modules

Source: Internet
Author: User
Tags thread class

Python provides multiple modules to support multithreaded programming, including thread,threading , and queue modules.
The thread module provides basic threading and locking support, while the threading module provides a higher level of more comprehensive thread management.
Queue module, users can create a queue data structure that is used to share between multiple threads.

Core tip : Avoid using the thread module
It is recommended to use a higher-level threading module for the following reasons:
The 1.threading module is more advanced, has better threading support, and some attributes in the thread module conflict with the threading module;
2. The low-level thread module has very few synchronization primitives (actually only one), while the threading module has many;
The 3.thread module has no control over when the process exits, and when the main thread ends, all other threads are forced to end without warning or proper cleanup;
At a minimum, the 4.threading module ensures that important sub-threads end before the process exits.
The 5.thread module does not support the concept of daemon threads (thread: When the main thread exits, all child threads are terminated, regardless of whether they are still working)

One. Avoid using the thread module, but be aware of its basic usage

import thread from time import sleep,ctime,strftimeloops = [4,2]def loop (Nloop, Nsec,lock): print ' Start loop ', Nloop, ' at: ', strftime ('%y-%m-%d%h:%m:%s ') sleep (nsec) print ' Loop ', Nloop, ' Done,at    : ', strftime ('%y-%m-%d%h:%m:%s ') lock.release () #释放锁def main (): print ' starting at: ', strftime ('%y-%m-%d%h:%m:%s ')         locks = [] Nloops = range (len (loops)) #[0, 1] for i in nloops:lock = Thread.allocate_lock () #获取LockType锁对象  Lock.acquire () #取得每个锁 (equivalent to "lock") Locks.append (lock) #一旦锁被锁上, you can add it to the lock list locks #print locks for I        In Nloops: #派生线程 #每个线程会调用loop () function and pass the loop number, sleep time, and lock Thread.start_new_thread (loop, (I,loops[i],locks[i]) for the thread Sleep (1) for I in Nloops:while locks[i].locked (): #暂停主线程, wait until all locks are released before continuing with pass print ' All do at: ', strftime ('%y-%m-%d%h:%m:%s ') if __name__ = = ' __main__ ': Main () 

two. Higher-level threading modules are recommended, functional programming method

The thread class of the Import threading#threading module has a join () method that allows the main thread to wait for all threads to finish executing from time import sleep,strftimeloops = [4,2,2]def Loop (nloop,nsec): print ' Start loop ', Nloop, ' at: ', strftime ('%y-%m-%d%h:%m:%s ') sleep (nsec) print ' Loop ', Nloop, ' d    One,at: ', strftime ('%y-%m-%d%h:%m:%s ') def main (): print ' starting at: ', strftime ('%y-%m-%d%h:%m:%s ') threads = [] Nloops = Range (len (loops)) #[0, 1] for i in Nloops: #实例化Thread (call Thread () and before call Thread.start_new_thread () maximum difference Is that the new thread does not immediately start executing t = Threading. Thread (target=loop,args= (I,loops[i])) #这是个非常有用的同步功能 Threads.append (t) for I in Nloops: #启动线程 #当所有线程都分配完成后 , by invoking the start () method of each thread to let them execute, instead of executing threads[i].start () for I in Nloops: #为每个线程调用join () method, join (        Method waits for the thread to end, or when the time-out is provided, the timeout is reached.            The Threads[i].join () #join () method is useful only if you need to wait for the thread to complete #join () method does not need to be called at all, and once the thread starts, they will execute until the given function completes. print ' All do at: ', strftime ('%y-%m-%d%h:%m:%s ') print loop.__name__ if __name__ = = ' __main__ ': Main () 

three. The object-oriented programming method of the threading module, using the callable class

Import threadingfrom Time Import sleep,strftimeloops = [4,2]class ThreadFunc (object): #添加ThreadFunc类 def __init__ (self,    Func,args,name = "): #构造方法设定函数自身, string of function arguments and function names Self.name = name Self.func = Func Self.args = args def __call__: #__call__特殊方法直接调用 Self.func (*self.args) def Loop (nloop,nsec): print ' Start loop ', Nloop, ' at: ',    Strftime ('%y-%m-%d%h:%m:%s ') sleep (nsec) print ' Loop ', Nloop, ' done at: ', strftime ('%y-%m-%d%h:%m:%s ') def main (): print ' Starting at: ', strftime ('%y-%m-%d%h:%m:%s ') threads = [] Nloops = range (len (loops)) for i in Nloops: # Instantiate the thread class object T = Threading.        Thread (Target=threadfunc (Loop, (i,loops[i)), loop.__name__)) #分配线程 Threads.append (t) for I in Nloops:     The Threads[i].start () #真正通过start () method starts the thread for I in Nloops:threads[i].join () #等待线程完成         print ' All do at: ', strftime ('%y-%m-%d%h:%m:%s ') if __name__ = = ' __main__ ': Main ()

four. Threading Module Object-oriented extension, deriving subclasses of thread and creating instances of subclasses

' Import threadingfrom time import sleep,strftimeloops = [4,2]class MyThread (threading. Thread): def __init__ (self,func,args,name= "): Threading. Thread.__init__ (Self) constructor method for the #MyThread子类的构造方法必须先调用基类 (that is, the parent class) Self.name = Name Self.func = Func sel F.args = args def run (self): #之前的特殊方法__call__在这里必须要写成run () Self.func (*self.args) def Loop (nloop,nsec): pri NT ' Start loop ', Nloop, ' at: ', strftime ('%y-%m-%d%h:%m:%s ') sleep (nsec) print ' Loop ', Nloop, ' do at: ', strftime ('%y-%m- %d%h:%m:%s ') def main (): print ' starting at: ', strftime ('%y-%m-%d%h:%m:%s ') threads = [] Nloops = range (len (loops         )) #print nloops for i in nloops:t = MyThread (Loop, (I,loops[i]), loop.__name__) threads.append (t) For I in Nloops:threads[i].start () for I in Nloops:threads[i].join () print ' All Done at: ', strftime ('%y-%m-%d%h:%m:%s ') if __name__ = = ' __main__ ': Main () "#Thread子类MyTHread #将上面的代码独立作为一个模块, save the results in the instance properties Self.res, and create a new method GetResult () to get this value import threadingfrom time import Strftimeclass MyThread (Threading. Thread): def __init__ (self,func,args,name= "): Threading. Thread.__init__ (self) self.name = name Self.func = Func Self.args = args def getresult (sel        f): Return Self.res def run (self): print ' starting ', Self.name, ' at: ', strftime ('%y-%m-%d%h:%m:%s ')    Self.res = Self.func (*self.args) print Self.name, ' finished at: ', strftime ('%y-%m-%d%h:%m:%s ')

  

Reference "Python Core Programming" (3rd edition)

 

Python learning Experience (vii) in-depth understanding of threading multithreaded Modules

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.