[Python]多线程入门

原文:http://blog.csdn.net/ice110956/article/details/28421807

Python的多线程有两种实现方法:

函数,线程类

1.函数

调用thread模块中的start_new_thread()函数来创建线程,以线程函数的形式告诉线程该做什么

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. # -*- coding: utf-8 -*-  
  2. import thread  
  3.    
  4.    
  5. def f(name):  
  6.     #定义线程函数  
  7.     print "this is " + name  
  8.    
  9.    
  10. if __name__ == '__main__':  
  11.     thread.start_new_thread(f, ("thread1",))  
  12.     #用start_new_thread()调用线程函数和其他参数  
  13.     while 1:  
  14.         pass  

 

不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用while 1这种方法解决。

2.线程类

调用threading模块,创建threading.Thread的子类来得到自定义线程类。

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. # -*- coding: utf-8 -*-  
  2. import threading  
  3.    
  4.    
  5. class Th(threading.Thread):  
  6.     def __init__(self, name):  
  7.         threading.Thread.__init__(self)  
  8.         self.t_name = name  
  9.         #调用父类构造函数  
  10.    
  11.     def run(self):  
  12.         #重写run()函数,线程默认从此函数开始执行  
  13.         print "This is " + self.t_name  
  14.    
  15. if __name__ == '__main__':  
  16.     thread1 = Th("Thread_1")  
  17.     thread1.start()  
  18.     #start()函数启动线程,自动执行run()函数  

 

threading.Thread类的可继承函数:

getName() 获得线程对象名称

setName() 设置线程对象名称

join() 等待调用的线程结束后再运行之后的命令

setDaemon(bool) 阻塞模式,True:父线程不等待子线程结束,False 等待,默认为False

isDaemon() 判断子线程是否和父线程一起结束,即setDaemon()设置的值

isAlive() 判断线程是否在运行

实例

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import threading  
  2. import time  
  3.    
  4.    
  5. class Th(threading.Thread):  
  6.     def __init__(self, thread_name):  
  7.         threading.Thread.__init__(self)  
  8.         self.setName(thread_name)  
  9.    
  10.     def run(self):  
  11.         print "This is thread " + self.getName()  
  12.         for i in range(5):  
  13.             time.sleep(1)  
  14.             print str(i)  
  15.         print self.getName() + "is over"  

join()阻塞等待

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if __name__ == '__main__':  
  2.     thread1 = Th("T1 ")  
  3.     thread1.start()  
  4.     #thread1.join()  
  5.     print "main thread is over"  

 

不带thread1.join(),得到如下结果:

This is thread T1 

main thread is over

0

1

2

T1 is over

不等待thread1完成,执行之后语句。

 

加了thread1.join(),得到如下结果:

This is thread T1

0

1

2

T1 is over

main thread is over

阻塞等待thread1结束,才执行下面语句

主线程等待

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if __name__ == '__main__':  
  2.     thread1 = Th("T1 ")  
  3.     thread1.setDaemon(True)  
  4.     #要在线程执行之前就设置这个量  
  5.     thread1.start()  
  6.     print "main thread is over"  

 

报错:Exception in thread T1  (most likely raised during interpreter shutdown):

也就是主线程不等待子线程就结束了。

多个子线程

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. if __name__ == '__main__':  
  2.     for i in range(3):  
  3.         t = Th(str(i))  
  4.         t.start()  
  5.     print "main thread is over"  

 

这里的t可同时处理多个线程,即t为线程句柄,重新赋值不影响线程。

这里奇怪的是,运行t.run()时,不会再执行其他线程。虽不明,还是用start()吧。暂且理解为start()是非阻塞并行的,而run是阻塞的。

线程锁

threading提供线程锁,可以实现线程同步。

 

[python] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import threading  
  2. import time  
  3.    
  4.    
  5. class Th(threading.Thread):  
  6.     def __init__(self, thread_name):  
  7.         threading.Thread.__init__(self)  
  8.         self.setName(thread_name)  
  9.    
  10.     def run(self):  
  11.         threadLock.acquire()  
  12.         #获得锁之后再运行  
  13.         print "This is thread " + self.getName()  
  14.         for i in range(3):  
  15.             time.sleep(1)  
  16.             print str(i)  
  17.         print self.getName() + " is over"  
  18.         threadLock.release()  
  19.         #释放锁  
  20.    
  21.    
  22. if __name__ == '__main__':  
  23.     threadLock = threading.Lock()  
  24.     #设置全局锁  
  25.     thread1 = Th('Thread_1')  
  26.     thread2 = Th('Thread_2')  
  27.     thread1.start()  
  28.     thread2.start()  

 

得到结果:

This is thread Thread_1

0

1

2

Thread_1 is over

This is thread Thread_2

0

1

2

Thread_2 is over

 

 
 
posted @ 2016-08-20 14:08  止战  阅读(463)  评论(0编辑  收藏  举报