您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2025/11/9 5:35:30发布15次查看
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模块,目前暂没有应用到。。。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product