本文主要是介绍线程对象threading.Thread汇总(tcy),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
汇总 1.threading中的方法属性及其实例。 2.thread创建及属性方法应用。 3.注1详解join,daemon的工作原理及实例。线程对象Thread 2018/9/21------------------------------------------------------------------------------ 1.class threading.Thread(group = None,target = None,name = None,args =(),kwargs = {},*,daemon = None )# 应始终使用关键字参数调用此构造函数。# 参数:# target:是run()方法调用的可调用对象。# name: 是线程名称。默认 “Thread- N ”# args: 是目标调用的参数元组。默认为()。# kwargs:是目标调用的关键字参数字典。默认为{}。------------------------------------------------------------------------------ 2.1.属性:name# getName() 获得线程对象名称# setName() 设置线程对象名称ident 线程标识符或None线程尚未启动。非零整数。# get_ident()daemon 守护程序线程(True)或不是#(默认False子线程随主线程一起结束)# ------------------------------------------------------------------------------ 2.2.方法start() 开始线程活动。#每个线程对象最多只能调用一次。run() 表示线程活动的方法。可在子类中重写此方法。join(timeout=None) 等待线程终止。参数:无参数: 阻塞调用线程;逐个执行每个线程完毕继续往下执行timeout: 线程运行最大时间,超时线程被回收,然后接着执行# 如线程执行时间小于参数则接着执行,不用一定要等待到参数表示的时间。# 原理:# 依次检验线程池中线程是否结束,无结束就阻塞直到线程结束,如结束则执行下一个线程# 1. 阻塞主进程,专注于执行多线程中的程序。# 2. 多线程join:依次执行各线程join方法,前1个结束才能执行后1个。# 3. 无参数,则等待到该线程结束,才开始执行下一个线程的join。# 4. timeout线程阻塞时间:timeout=2 线程运行2s后不管他,继续执行下面的代码。setDaemon(True) 设置为守护线程;# 含义:# 主线程A中创建子线程B,在主线程A中调用B.setDaemon()含义:# 主线程A设为守护线程,如A结束不管B是否完成一并和主线程A退出.# 不设置为守护线程,程序会被无限挂起,只有等待了所有线程结束它才结束。# 在start()调用之前设置;否则引发RuntimeErrorisDaemon() 判断线程是否随主线程一起结束is_alive() 检查线程是否在运行中'''总结:注11.当线程用join时该线程一定会被执行(此时不用考虑该线程是否daemon)2.当线程无join时看daemon(当daemon=True若该线程执行时间>主线程的运行时间该线程不能被完全执行。)''' # -------------------------------------------------------------------------------- 3.创建线程: ''' 3.1.函数创建''' import threading ,timedef run(a1, a2,t):print('[RunStart:a={};b={};] \n'.format(a1,a2))time.sleep(t)print('[RunEnd:{};time={}] \n'.format(threading.current_thread().name,time.time_ns()-start))start=time.time_ns()t1 = threading.Thread(target=run, args=(11, 12,1)) # 创建线程 t1.setDaemon(True) t1.start() # 开启线程 # t2 = threading.Thread(target=run, args=(21, 22,2)) t2.start() t2.join() # t3 = threading.Thread(target=run, args=(31, 32,3)) t3.start()time.sleep(1) print('[------MainThread end:time={}------] \n'.format(time.time_ns()-start)) ''' [RunStart:a=11;b=12;] [RunStart:a=21;b=22;] [RunEnd:Thread-1;time=1001057300] [RunEnd:Thread-2;time=2001114500] [RunStart:a=31;b=32;] [------MainThread end:time=3001171700------] [RunEnd:Thread-3;time=5001286100] ''' # ------------------------------------------------------------------------------''' 3.1.创建threading.Thread子类:class MyThread(threading.Thread):def __init__(self, n, x):threading.Thread.__init__(self)'''#threading.Thread.__init__(self, name = threadname)#group,target,name,args ,kwargs ,daemon#def run(self):#重构Thread类中的run'''class MyThread(threading.Thread):def __init__(self, *args, **kwargs):super(MyThread, self).__init__(*args, **kwargs) ''' import threading,time # class MyThread(threading.Thread):#继承threading.Threaddef __init__(self, x, time=0):threading.Thread.__init__(self)self.x = xself.time = timeself.thread_stop = Falsedef run(self):while not self.thread_stop:print('x=%d, Time=%s\n' %(self.x, time.ctime()))time.sleep(self.time)def stop(self):self.thread_stop = True # def test():t1 = MyThread(1)t1.time=1t2 = MyThread(2)t2.time=2t1.start()t2.start()time.sleep(2)t1.stop()t2.stop()return # test() ''' x=1, Time=Fri Sep 21 09:08:55 2018 x=2, Time=Fri Sep 21 09:08:55 2018 x=1, Time=Fri Sep 21 09:08:56 2018 x=1, Time=Fri Sep 21 09:08:57 2018------------------------------------------------------------------------------- 4.实例 ''' # ***************************************************************************** # 例1 计算子线程执行的时间# 注:sleep的时候是不会占用cpu的, 在sleep的时候操作系统会把线程暂时挂起。 import threading,time # def run(n,start_time):name=threading.current_thread().nametime1=time.time_ns()-start_timeprint('[RunStart:n=t-{};name={};time={};] \n'.format(n,name,time1))# 输出当前的线程time.sleep(1)print('......s1......\n')time.sleep(1)print('......s2......\n')time1 = time.time_ns() - start_timeprint('[RunEnd:n=t-{};name={};time={};] \n'.format(n, name, time1)) # start_time = time.time_ns() t_obj = [] # 定义列表用于存放子线程实例 # for i in range(3):t = threading.Thread(target=run, args=(i,start_time))t.start()t_obj.append(t)for tmp in t_obj:t.join() # 主线程就会等这些子线程执行完之后再执行。name=threading.current_thread().name time1 = time.time_ns() - start_time print('[------EndAll:name={};time={};------] \n'.format(name, time1)) '''[RunStart:n=t-0;name=Thread-1;time=1000100;] [RunStart:n=t-1;name=Thread-2;time=2000200;] [RunStart:n=t-2;name=Thread-3;time=2000200;] ......s1...... ......s1...... ......s1...... ......s2...... [RunEnd:n=t-0;name=Thread-1;time=2001114500;] ......s2...... [RunEnd:n=t-1;name=Thread-2;time=2002114600;] ......s2...... [RunEnd:n=t-2;name=Thread-3;time=2003114600;] [------EndAll:name=MainThread;time=2003114600;------] ''' # ***************************************************************************** # 实例2 统计当前活跃的线程数# 由于主线程比子线程快很多,当主线程执行active_count()时,其他子线程都还没执行完毕,# 因此利用主线程统计的活跃的线程数num = sub_num(子线程数量)+1(主线程本身)# 在python内部默认会等待最后一个进程执行完再exit(),或者说python内部在此时有一个隐藏的join()。 import threading,timedef run(n,time1):print("task", n)time.sleep(time1) #此时子线程停1stime1=1;time2=0.5; for i in range(3):t = threading.Thread(target=run, args=("t-%s" % i,time1))t.start()time.sleep(time2) #主线程停0.5秒 print(threading.active_count()) #输出当前活跃的线程数""" task t-0 task t-1 task t-2 4 # 当把time1=0.5;time2=1;时当前活跃的线程数=1 """ # ***************************************************************************** # 实例3.守护进程# setDaemon(True)把所有子线程变成主线程守护线程,当主进程结束子线程不管是否完成也结束# 所以当主线程结束后,整个程序就退出了。 import threading,timedef run(n):print("start task:{} \n".format(n))time.sleep(1) #此时子线程停1sprint('.....s1......\n')time.sleep(1)print('.....s2......\n')time.sleep(1)print("end task:{} \n".format(n)) # for i in range(3):t = threading.Thread(target=run, args=(i,))t.setDaemon(True) #把子进程设置为守护线程,必须在start()之前设置t.start()time.sleep(0.5) #主线程停0.5秒 print("EndAll: active_count={} \n".format(threading.active_count()))""" start task: t-0 start task: t-1 start task: t-2 EndAll: active_count= 4 #若没有t.setDaemon(True)语句,则显示如下: start task:0 start task:1 start task:2 EndAll: active_count=4 .....s1...... .....s1...... .....s1...... .....s2...... .....s2...... .....s2...... end task:1 end task:0 end task:2 """ # ***************************************************************************** # 实例4import threading, zipfileclass AsyncZip(threading.Thread):#def __init__(self, infile, outfile):threading.Thread.__init__(self)self.infile = infileself.outfile = outfile#def run(self):f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)f.write(self.infile)f.close()print('Finished background zip of:', self.infile) # background = AsyncZip('mydata.txt', 'myarchive.zip') background.start() print('The main program continues to run in foreground.') background.join() # Wait for the background task to finish print('Main program waited until background was done.') # ***************************************************************************** ------------------------------------------------------------------------------- 注1:
''' threading.Thread 中join daemon的工作原理 2018/9/21------------------------------------------------------------------------------- ''' ''' 1.测试程序'''import threading ,timedef run(a1, a2,t): print('1.a1=',a1,'a2=',a2,threading.enumerate(),'\\n') time.sleep(t) print('2.end thread==================>',threading.current_thread().name,'time=',time.time_ns()-start)start=time.time_ns() b=True t1 = threading.Thread(target=run, args=(11, 12,5)) # 创建线程 t1.setDaemon(b) t1.start() # 开启线程 # t1.join() t2 = threading.Thread(target=run, args=(21, 22,4)) t2.setDaemon(b) t2.start() # t2.join() t3 = threading.Thread(target=run, args=(31, 32,5)) t3.setDaemon(b) # print('==========',t3.daemon) t3.start() t1.join() t2.join() t3.join() time.sleep(1) print('3.MainThread end...+++++++++++++++++++++++++++++++++',time.time_ns()-start)''' ----------------------------------------------------------------------------------- 2.结果分析 ''' #1.1.daemon=False,无join运行全部线程;主线程运行完会等子线程完成在退出 #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #2.1.daemon=False, # t1.start();t1.join() #先运行线程t1 # t2.start();t2.join() #t1运行完成在运行t2 # t3.start();t3.join() #t2运行完成在运行t3 # ... #t3运行完成在运行后面的主线程 # #2.2.daemon=False, # t1.start();t2.start();t3.start(); #线程t1,t2,t3依次开始运行 # t1.join();t2.join();t3.join() #t1,t2,t3全部运行完成在运行后面的主线程 # #2.3.daemon=False, # t1.start(); # t2.start(); #线程t1,t2依次开始运行 # t2.join() #等待t2运行完成后 # #上面程序t2未运行完不向下进行,暂停在此处;当t2运行完成,不论t1是否完成都向下进行 # t3.start(); # ... # #t3和主线程和t1(若t1未运行完成)同时运行,谁快谁先完成,等全部完成才退出程序;程序都全部执行。 # # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #3.1.t1,t2,t3.daemon=True, #无join运行全部线程;主线程运行完会不等子线程完成全部退出 # #3.2.t1,t3.daemon=True, #无join运行全部线程;主线程运行完会不等子线程t1,t3完成全部退出 # (但线程t2一定会运行,他和主线程的退出顺序取决于各自的运行时间) # #3.3.t1,t2,t3.daemon=True, # t1.start;t1.join; #先运行线程t1 # t2.start;t2.join; #t1运行完成在运行t2 # t3.start;t3.join #t2运行完成在运行t3 # ... #t3运行完成在运行后面的主线程 # #3.4.t1,t2,t3.daemon=True, # t1,t2,t3.start; # t1,t2,t3.join #t1,t2,t3同时运行等待全部完成再运行主线程 ''' ------------------------------------------------------------------------------------------- 总结:1.当线程用join时该线程一定会被执行(此时不用考虑该线程是否daemon) 2.当线程无join时看daemon(当daemon=True若该线程执行时间>主线程的运行时间该线程不能被完全执行。) ------------------------------------------------------------------------------------------- '''
threading方法 2018/8/19
# threading模块创建多个线程;由于GIL锁的存在在多线程里面其实是快速切换------------------------------------------------------------------------------- 1.threading 1.1.应用 # 利用多核使用 multiprocessing或concurrent.futures.ProcessPoolExecutor。 # 要同时运行多个I / O绑定任务,则线程仍然是一个合适的模型 1.2.特点 # 模块设计基于Java线程模型。没有优先级,没有线程组,线程不能被销毁,停止,暂停,恢复或中断。 # Java的Thread类的静态方法在实现时会映射到模块级函数。 1.3.类层次 builtins.object _thread._local Barrier Condition Event Semaphore BoundedSemaphore Thread Timer1.4. with语句 # 应用: # Lock,RLock,Condition, Semaphore,和BoundedSemaphore对象可用with # 模块acquire()和 release()方法所有对象都可以用作with 语句的上下文管理器with some_lock: # do something...#相当于: some_lock.acquire() try: # do something... finally: some_lock.release()------------------------------------------------------------------------------- 2.1.模块常量: threading.TIMEOUT_MAX 允许最大值超时阻断功能;超时引发 OverflowError # 应用:参数Lock.acquire(),RLock.acquire(),Condition.wait() ------------------------------------------------------------------------------- 2.2.模块方法: threading.active_count() 返回当前活动线程数。=len(threading.enumerate()) threading.current_thread() 返回当前线程(对应调用者控制线程)或虚拟线程对象。 threading.get_ident() 返回当前线程“线程标识符”非零整数。 threading.enumerate() 返回当前活动所有线程列表。含守护线程虚拟线程主线程 threading.main_thread() 返回主线程对象 threading.settrace(func ) 从threading模块启动所有线程设置跟踪功能。 # 在调用sys.settrace()其run()方法之前为每个线程 传递 func。 threading.setprofile(func ) 从threading模块启动所有线程设置配置文件功能。 # 在调用sys.setprofile()其run()方法之前为每个线程 传递 func。 threading.stack_size(size=0) 返回创建新线程时使用线程堆栈大小。 # size=0(使用平台或已配置默认值)或至少32,768(32 KiB)正整数。建议4096倍数------------------------------------------------------------------------------ 2.3.线程局部数据 mydata = threading.local() mydata.x = 1------------------------------------------------------------------------------ 3.实例:
import threading,timedef run(n):# threading 模块方法tc=threading.current_thread()tc.setName('Thread...{}'.format(n)) # 设置线程对象名称print('threading方法:')print('最大值超时{} ='.format(n),threading.TIMEOUT_MAX)# 4294967.0print('当前线程{} ='.format(n), tc,tc.name,tc.getName())# 当前线程t - 0 = < Thread(Thread...t - 0, started 12108) > Thread...t - 0# 当前线程t - 1 = < Thread(Thread...t - 1, started 2388) > Thread...t - 1# 当前线程t - 2 = < Thread(Thread...t - 2, started 11852) > Thread...t - 2print('线程标识符{} ='.format(n), threading.get_ident(),tc.ident)# 线程标识符t - 0 = 12108 threading.get_ident()不能用在类实例中# 线程标识符t - 1 = 2388# 线程标识符t - 2 = 11852print('主线程 {} ='.format(n), threading.main_thread())# 主线程 t - x = < _MainThread(MainThread, started 8048) >print('新线程堆栈{} ='.format(n), threading.stack_size())#0print('守护线程{} ='.format(n), tc.isDaemon())#falseprint('线程运行中{} ='.format(n), tc.is_alive())#truetime.sleep(1) #此时子线程停1s
for n in range(3):t = threading.Thread(target=run, args=("t-%s" % n,))t.start()# threading.Thread 方法print('t threading.Thread 方法:')print('t当前线程{} ='.format(n), t, t.name, t.getName())# t当前线程0 = < Thread(Thread...t - 0, started 12108) > Thread...t - 0# t当前线程1 = < Thread(Thread...t - 1, started 2388) > Thread...t - 1# t当前线程2 = < Thread(Thread...t - 2, started 11852) > Thread...t - 2print('t线程标识符{} ='.format(n), t.ident)print('t守护线程{} ='.format(n), t.isDaemon(),t.daemon)#falseprint('t线程运行中{} ='.format(n), t.is_alive())#trueprint('===>',[i for i in dir(t)])str1=[i for i in dir(t) if ((i.find('__') == -1) and (i.find('_') == -1))]print('===>',str1) # ===> ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_args', '_bootstrap', '_bootstrap_inner', '_daemonic', '_delete', '_exc_info', '_ident', '_initialized', '_is_stopped', '_kwargs', '_name', '_reset_internal_locks', '_set_ident', '_set_tstate_lock', '_started', '_stderr', '_stop', '_target', '_tstate_lock', '_wait_for_tstate_lock', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'is_alive', 'join', 'name', 'run', 'setDaemon', 'setName', 'start'] # ===> ['daemon', 'getName', 'ident', 'isAlive', 'isDaemon', 'join', 'name', 'run', 'setDaemon', 'setName', 'start']time.sleep(0.5) #主线程停0.5秒 print('活跃的线程数=',threading.active_count(),len(threading.enumerate()),threading.enumerate()) #4 4 # [<_MainThread(MainThread, started 11080)>, <Thread(Thread...t-0, started 9700)>, # <Thread(Thread...t-1, started 9360)>, <Thread(Thread...t-2, started 11304)>]print("MainThread=",threading.main_thread()) # MainThread= <_MainThread(MainThread, started 11080)> # -----------------------------------------------------------------------------
这篇关于线程对象threading.Thread汇总(tcy)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!