多线程threading模块用法 -《狗嗨默示录》-

threading提供了一个比thread模块更高层的API来提供线程的并发性。这些线程并发运行并共享内存。 python

        下面来看threading模块的具体用法: 多线程

 

     1、Thread的使用 目标函数能够实例化一个Thread对象,每一个Thread对象表明着一个线程,能够经过start()方法,开始运行。并发

     这里对使用多线程并发,和不适用多线程并发作了一个比较:app

首先是不使用多线程的操做:函数

代码以下:spa

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#compare for multi threads import time def worker(): print "worker" time.sleep(1) return if __name__ == "__main__": for i in xrange(5): worker()

执行结果以下:线程

   

下面是使用多线程并发的操做:code

代码以下:对象

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading import time def worker(): print "worker" time.sleep(1) return for i in xrange(5): t = threading.Thread(target=worker) t.start()

能够明显看出使用了多线程并发的操做,花费时间要短的不少。blog

 

2、threading.activeCount()的使用,此方法返回当前进程中线程的个数。返回的个数中包含主线程。

代码以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#current's number of threads import threading import time def worker(): print "test" time.sleep(1) for i in xrange(5): t = threading.Thread(target=worker) t.start() print "current has %d threads" % (threading.activeCount() - 1)

 

3、threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表。

代码以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#test the variable threading.enumerate() import threading import time def worker(): print "test" time.sleep(2) threads = [] for i in xrange(5): t = threading.Thread(target=worker) threads.append(t) t.start() for item in threading.enumerate(): print item print for item in threads: print item

 

4、threading.setDaemon()的使用。设置后台进程。

代码以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#create a daemon import threading import time def worker(): time.sleep(3) print "worker" t=threading.Thread(target=worker) t.setDaemon(True) t.start() print "haha"

能够看出worker()方法中的打印操做并无显示出来,说明已经成为后台进程。

相关文章
相关标签/搜索