因为线程是操作零碎间接支持的执行单位,因而,初级言语通常都内置多线程的支持,Python也没有破例,而且,Python的线程是真实的Posix Thread,而没有是模仿进去的线程。
Python的规范库提供了两个模块:_thread以及threading,_thread是低级模块,threading是初级模块,对_thread进行了封装。绝年夜少数状况下,咱们只要要应用threading这个初级模块。(保举学习:Python视频教程)
启动一个线程就是把一个函数传入并创立Thread实例,而后挪用start()开端执行:
import time, threading# 新线程执行的代码:def loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n = n + 1 print('thread %s >>> %s' % (threading.current_thread().name, n)) time.sleep(1) print('thread %s ended.' % threading.current_thread().name) print('thread %s is running...' % threading.current_thread().name) t = threading.Thread(target=loop, name='LoopThread') t.start() t.join() print('thread %s ended.' % threading.current_thread().name)
执行后果以下:
thread MainThread is running... thread LoopThread is running... thread LoopThread >>> 1 thread LoopThread >>> 2 thread LoopThread >>> 3 thread LoopThread >>> 4 thread LoopThread >>> 5 thread LoopThread ended. thread MainThread ended.
因为任何过程默许就会启动一个线程,咱们把该线程称为主线程,主线程又能够启动新的线程,Python的threading模块有个current_thread()函数,它永远前往以后线程的实例。主线程实例的名字叫MainThread,子线程的名字正在创立时指定,咱们用LoopThread定名子线程。名字仅仅正在打印时用来显示,齐全不其余意思,假如没有起名字Python就主动给线程定名为Thread-1,Thread-2……
更多Python相干技巧文章,请拜访Python教程栏目进行学习!
以上就是python中若何装置threading的具体内容,更多请存眷资源魔其它相干文章!
标签: Python python教程 python编程 python使用问题
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!