Heim  >  Artikel  >  Backend-Entwicklung  >  Python中多线程的创建及基本调用方法

Python中多线程的创建及基本调用方法

WBOY
WBOYOriginal
2016-07-22 08:56:241052Durchsuche

1. 多线程的作用
简而言之,多线程是并行处理相互独立的子任务,从而大幅度提高整个任务的效率。

2. Python中的多线程相关模块和方法
Python中提供几个用于多线程编程的模块,包括thread,threading和Queue等
thread模块提供了基本的线程和锁的支持,除产生线程外,也提供基本的同步数据结构锁对象,其中包括:
start_new_thread(function, args kwargs=None)  产生一个新的线程来运行给定函数
allocate_lock()  分配一个LockType类型的锁对象
exit() 让线程退出
acquire(wait=None) 尝试获取锁对象
locked()  如果获取了锁对象返回TRUE,否则返回FALSE
release()  释放锁
threading提供了更高级别,功能更强的线程管理功能
Thread类 表示一个线程的执行的对象
Lock 锁原语对象
RLock 可重入锁对象,使单线程可以再次获得已经获取锁
queue模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构
可用于进程间的通讯,让各个线程之间共享数据
模块函数queue(size)  创建一个大小为size的Queue对象
queue对象函数 qsize()  返回队列大小
empty()  队列为空返回True,否则返回False
put(item, block=0)  把ITEM放到队列中,block不为0,函数会一直阻塞到队列中
get(block=0) 从队列中取一个对象,若果给block,函数会一直阻塞到队列中有对象为止

3.示例
目前Python的lib中对多线程编程提供两种启动方法,一种是比较基本的thread模块中start_new_thread方法,在线程中运行一个函数, 另一种是使用集成threading模块的线程对象Thread类。
目前所用到的,是旧版本中调用thread模块中的start_new_thread()函数来产生新的线程
相比而言,thread.start_new_thread(function,(args[,kwargs]))实现机制其实与C更为类似,其中function参数是将要调用的线程函数;(args[,kwargs])是将传递给待创建线程函数的参数组成的元组类型,其中kwargs是可选的参数。新创建的线程结束一般依靠线程函数的执行结束自动退出,或者在线程函数中调用thread.exit()抛出SystemExit exception,达到线程退出的目的。

print "=======================thread.start_new_thread启动线程============="  
import thread  
#Python的线程sleep方法并不是在thread模块中,反而是在time模块下  
import time  
def inthread(no,interval):  
  count=0  
  while count<10:  
    print "Thread-%d,休眠间隔:%d,current Time:%s"%(no,interval,time.ctime())  
    #使当前线程休眠指定时间,interval为浮点型的秒数,不同于Java中的整形毫秒数  
    time.sleep(interval)  
    #Python不像大多数高级语言一样支持++操作符,只能用+=实现  
    count+=1  
  else:  
    print "Thread-%d is over"%no  
    #可以等待线程被PVM回收,或主动调用exit或exit_thread方法结束线程  
    thread.exit_thread()  
#使用start_new_thread函数可以简单的启动一个线程,第一个参数指定线程中执行的函数,第二个参数为元组型的传递给指定函数的参数值  
thread.start_new_thread(inthread,(1,2))  
  #线程执行时必须添加这一行,并且sleep的时间必须足够使线程结束,如本例  
  #如果休眠时间改为20,将可能会抛出异常  
time.sleep(30)  
'''  

使用这种方法启动线程时,有可能出现异常

Unhandled exception in thread started by 
Error in sys.excepthook: 
Original exception was: 

解决:启动线程之后,须确保主线程等待所有子线程返回结果后再退出,如果主线程比子线程早结束,无论其子线程是否是后台线程,都将会中断,抛出这个异常
若没有响应阻塞等待,为避免主线程提前退出,必须调用time.sleep使主线程休眠足够长的时间,另外也可以采用加锁机制来避免类似情况,通过在启动线程的时候,给每个线程都加了一把锁,直到线程运行介绍,再释放这个锁。同时在Python的main线程中用一个while循环来不停的判断每个线程锁已释放。

import thread;  
from time import sleep,ctime;  
from random import choice  
#The first param means the thread number  
#The second param means how long it sleep  
#The third param means the Lock  
def loop(nloop,sec,lock):  
  print "Thread ",nloop," start and will sleep ",sec;  
  sleep(sec);  
  print "Thread ",nloop," end ",sec;  
  lock.release();  
  
def main():  
  seconds=[4,2];  
  locks=[];  
  for i in range(len(seconds)) :  
    lock=thread.allocate_lock();  
    lock.acquire();  
    locks.append(lock);  
      
  print "main Thread begins:",ctime();  
  for i,lock in enumerate(locks):  
    thread.start_new_thread(loop,(i,choice(seconds),lock));  
  for lock in locks :  
    while lock.locked() :   
      pass;  
  print "main Thread ends:",ctime();  
  
if __name__=="__main__" :  
  main();  

很多介绍说在新python版本中推荐使用Threading模块,目前暂没有应用到。。。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn