本文摘自php中文网,作者(*-*)浩,侵删。
由于线程是操作系统直接支持的执行单元,因此,高级语言通常都内置多线程的支持,Python也不例外,并且,Python的线程是真正的Posix Thread,而不是模拟出来的线程。
Python的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。(推荐学习:Python视频教程)
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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)
|
阅读剩余部分
相关阅读 >>
学Python要c语言基础么
Python怎么加注释
Python全栈工程师是干什么的
Python中tuple指什么
Python函数之id函数
bool函数怎么用?
剖析Python垃圾回收机制
Python和r哪个更难
使用Python创建员工信息表的实例代码
记录一次简单的Python爬虫实例
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python中如何安装threading