python中threading模块详解(一)

来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html

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

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

一、Thread的使用 目标函数可以实例化一个Thread对象,每个Thread对象代表着一个线程,可以通过start()方法,开始运行。

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

首先是不使用多线程的操作:

代码如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
#compare for multi threads
import time
 
def worker():
    print "worker"
    time.sleep(1)
    return
 
if __name__ == "__main__":
    for i in xrange(5):
        worker()

执行结果如下:

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

代码如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
import threading
import time
 
def worker():
    print "worker"
    time.sleep(1)
    return
 
for i in xrange(5):
    t = threading.Thread(target=worker)
    t.start()

可以明显看出使用了多线程并发的操作,花费时间要短的很多。

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

代码如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python
#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)

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

代码如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python
#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

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

代码如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
#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()方法中的打印操作并没有显示出来,说明已经成为后台进程。

python中threading模块详解(一)的更多相关文章

  1. Python中time模块详解

    Python中time模块详解 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. ...

  2. python中socket模块详解

    socket模块简介 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket.socket通常被叫做"套接字",用于描述IP地址和端口,是一个通信 ...

  3. python中常用模块详解二

    log模块的讲解 Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适: logger提供了应用程序可以直接使用的接口API: handler将(logger创建的 ...

  4. Python中time模块详解(转)

    在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. 在开始之前,首先要说明这几点: ...

  5. python中常用模块详解一

    1.time 模块 import time s = time.localtime() # 把时间转化成格式化的时间,通过. 取得里面的年月日等 struct_time 格式 time.struct_t ...

  6. Python中pymysql模块详解

    安装 pip install pymysql 使用操作 执行SQL #!/usr/bin/env pytho # -*- coding:utf-8 -*- import pymysql # 创建连接 ...

  7. (转)python标准库中socket模块详解

    python标准库中socket模块详解 socket模块简介 原文:http://www.lybbn.cn/data/datas.php?yw=71 网络上的两个程序通过一个双向的通信连接实现数据的 ...

  8. python之OS模块详解

    python之OS模块详解 ^_^,步入第二个模块世界----->OS 常见函数列表 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows ...

  9. python之sys模块详解

    python之sys模块详解 sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧! sys模块的常见函数列表 sys.argv: 实现从程序外部向程序传 ...

随机推荐

  1. css知识点积累

    关于样式的优先级问题: !important > style > [ id > class > tag ];  z-index 的属性用法: z-index属性是用来设置元素的 ...

  2. ssh下:系统初始化实现ServletContextListener接口时,获取spring中数据层对象无效的问题

    想要实现的功能:SSH环境下,数据层都交由Spring管理:在服务启动时,将数据库中的一些数据加载到ServletContext中缓存起来. 系统初始化类需要实现两个接口: ServletContex ...

  3. 解决Ubuntu 下 vi编辑器不能使用方向键和退格键问题

    转自:http://blog.csdn.net/sky101010ws/article/details/51012103 使用vi命令时,不能正常编辑文件,使用方向键时老是出现很多字母 这个问题主要是 ...

  4. 使用Android应用调用Web Service

    Java本身提供了丰富的Web  Service支持,比如Sun公司指定的JAX-WS  2规范,还有Apache开源组织所提供的Axis1.Axis2.CXF等,这些技术不仅可以用于非常方便地对外提 ...

  5. java中怎么在table上显示数据

    连接oracle:String result = ""; // 查询结果字符串 String sql = "select * from test"; // SQ ...

  6. HDU 1171 背包

    Big Event in HDU Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  7. POJ 2226 最小点覆盖(经典建图)

    Muddy Fields Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8881   Accepted: 3300 Desc ...

  8. 为speedphp最新版添加 仿Yii 的简易版 数据验证 支持不同场景,自定义回调

    给个意见或建议吧 扩展一个Model基类 <?php class BaseModel extends Model{ use ValidationRules; public function ru ...

  9. 使用excel快速制表 拒绝粗心

    办公室打印个表格 使用了word打印后 发现 id重复很多 只好网上找了点excel 2003资料 学习小 快速制作表格 新建一个excel文件. 在新建excel中,用鼠标选中需要的表格行数列数,然 ...

  10. 【转】Nginx+Tomcat+Memcached集群

    Tomcat集群session同步方案有以下几种方式: 使用tomcat自带的cluster方式,多个tomcat间自动实时复制session信息,配置起来很简单.但这个方案的效率比较低,在大并发下表 ...