<标准库> threading模块基本用法
本帖最后由 戴宇轩 于 2015-3-21 11:32 编辑threading提供了一个比thread模块更高层的封装来提供线程的并发性, 这些线程并发运行并共享内存
下面来看threading模块的具体用法:
1. threading.Thread
可以实例化一个Thread对象, 每个Thread对象代表着一个线程, 可以通过start()方法开始运行
这里对使用多线程并发,和不适用多线程并发做了一个比较:
首先是不使用多线程的操作:import time
def worker():
print('worker')
time.sleep(1)
start_time = time.clock()
for i in range(5):
worker()
print('[用时 %d 秒]' % (time.clock() - start_time))worker
worker
worker
worker
worker
[用时 5 秒]下面是使用多线程的操作:import threading
import time
def worker():
print('worker')
time.sleep(1)
start_time = time.clock()
for i in range(5):
thread = threading.Thread(target=worker)
thread.start()
print('[用时 %d 秒]' % (time.clock() - start_time))worker
worker
worker
worker
worker
[用时 1 秒]可以明显看出使用了多线程并发的操作, 花费时间要短的很多
2. threading.activeCount()
此方法返回当前进程中线程的个数, 返回的个数中包含主线程import threading
import time
def worker():
print('test')
time.sleep(1)
for i in range(5):
thread = threading.Thread(target=worker)
thread.start()
print('共有 %d 个线程(包括主线程)' % (threading.activeCount()))test
test
test
test
test
共有 6 个线程(包括主线程)
3. threading.enumerate()
此方法返回当前运行中的Thread对象列表import threading
import time
def worker():
print('test')
time.sleep(2)
for i in range(5):
thread = threading.Thread(target=worker)
thread.start()
for item in threading.enumerate():
print(item)test
test
test
test
test
<_MainThread(MainThread, started -1218901696)>
<Thread(Thread-1, started -1220478144)>
<Thread(Thread-2, started -1229980864)>
<Thread(Thread-5, started -1257243840)>
<Thread(Thread-3, started -1240466624)>
<Thread(Thread-4, started -1248855232)>
4. threading.setDaemon()
设置进程为后台进程import threading
import time
def worker():
time.sleep(3)
print('worker')
thread = threading.Thread(target=worker)
thread.setDaemon(True)
thread.start()
print('Finish!')Finish!可以看出worker()方法中的打印操作并没有显示出来, 说明它已经成为后台进程
实习版主好勤奋~~{:9_237:}
加油~~{:9_231:} 6666666666666 赛高 {:10_279:}
页:
[1]