标签:
摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html
以及:http://blog.chinaunix.net/uid-11131943-id-2906286.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 threadsimport timedef worker(): print "worker" time.sleep(1) returnif __name__ == "__main__": for i in xrange(5): worker() |
执行结果如下:
下面是使用多线程并发的操作:
代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/pythonimport threadingimport timedef worker(): print "worker" time.sleep(1) returnfor 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 threadsimport threadingimport timedef 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 threadingimport timedef 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 itemprintfor 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 daemonimport threadingimport timedef worker(): time.sleep(3) print "worker"t=threading.Thread(target=worker)t.setDaemon(True)t.start()print "haha" |

可以看出worker()方法中的打印操作并没有显示出来,说明已经成为后台进程。
python线程 threading.Thread 条件变量 同步线程
在用python的threading.Thread编写多线程程序时,最简单的就是是用锁,为使线程之间保持同步,可以使用threading.Condition() 条件变量
思路:
1.分析哪一块空间需要多线程读写,抽象出一个共享空间类,对共享空间设置读方法(get)和写方法(set)
2.为使读线程和写线程同步,可以用threading.Condition()产生一个条件,同一个条件有wait()和notify()
notifyAll()方法,wait使线程自己进入block(阻塞)状态,一个线程的notify可以使同一个条件变量中block
的线程得到运行的机会。notifyAll通知所有被阻塞的线程进入runnable状态。
3.所有对共享空间操作的方法(read or write)都封闭在acquire()和release()中间
========以下实例简单明了==================
|
|
=============================================================================
|
|
=============================================================================
|
|
==============================测试代码===============================
|
|
标签:
原文地址:http://www.cnblogs.com/j6-2/p/4645490.html