|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 戴宇轩 于 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!')
复制代码 可以看出worker()方法中的打印操作并没有显示出来, 说明它已经成为后台进程
|
评分
-
查看全部评分
|