博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

threading 模块

Posted on 2015-07-06 16:08  bw_0927  阅读(139)  评论(0)    收藏  举报

http://c4fun.cn/blog/2014/05/06/python-threading/

http://www.runoob.com/python/python-multithreading.html

 http://blog.csdn.net/jgood/article/details/4305604

http://www.cszhi.com/20130528/python-threading.html

 

python里面的线程,如果抛出异常是不会影响主线程和其他线程的 

 

http://www.cnblogs.com/alan-babyblog/p/5325071.html    

setDaemon()  vs join

1、join ()方法:主线程A中,创建了子线程B,并且在主线程A中调用了B.join(),那么,主线程A会在调用的地方等待,直到子线程B完成操作后,才可以接着往下执行

2、setDaemon()方法。主线程A中,创建了子线程B,并且在主线程A中调用了B.setDaemon(), 把B设置为daemon线程

(The entire Python program exits when no alive non-daemon threads are left.)
设置为daemon的线程会随着主线程的退出而结束; 非daemon线程会阻塞主线程的退出

没有设置daemon的线程会继承父线程的状态,主线程默认是非daemon线程(Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.)

daemon的使用场景是:你需要一个始终运行的进程,用来监控其他服务的运行情况,或者发送心跳包或者类似的东西,你创建了这个进程都就不用管它了,他会随着主线程的退出出而退出了

如果主线程退出,守护线程也会自动退出。而,非守护线程则不然,你必须不断的轮询来终止一个非守护线程
 
如果你设置一个线程为守护线程,,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出。 
如果你的主线程在退出的时候,不用等待那些子线程完成,那就设置这些线程的daemon属性。即,在线程开始(thread.start())之前,调用setDeamon()函数,设定线程的daemon标志。(thread.setDaemon(True))就表示这个线程“不重要”。
 
 

 

创建线程的两种方法

 

def threadFunction():
    for i in range(10):
        print 'ThreadFuction - %d'%i
        time.sleep(random.randrange(0,2))


class ThreadClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self);
        
    def run(self):
        for i in range(10):
            print 'ThreadClass - %d'%i
            time.sleep(random.randrange(0,2))

if __name__ == '__main__':
    tFunc = threading.Thread(target = threadFunction);
    tCls  = ThreadClass()
    tFunc.start()
    tCls.start()

  


执行结果如下,可以看到两个线程在交替打印。至于空行和一行多个输出,是因为Py的print并不是线程安全的,在当前线程的print打印了部分内容后,准备打印换行之前,被别的线程中的print抢先,在换行之前打印了其它的内容。

ThreadFuction - 0
ThreadFuction - 1
ThreadFuction - 2
ThreadClass - 0
ThreadFuction - 3
ThreadClass - 1
ThreadFuction - 4
ThreadClass - 2
ThreadClass - 3
ThreadClass - 4ThreadFuction - 5

ThreadClass - 5
ThreadClass - 6
ThreadClass - 7
ThreadClass - 8
ThreadFuction - 6ThreadClass - 9

ThreadFuction - 7
ThreadFuction - 8
ThreadFuction - 9

 

Thread类的构造函数定义如下

 

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 留作ThreadGroup扩展使用,一般没什么用
target:新线程的任务函数名
name:  线程名,一般也没什么用
args:  tuple参数
kwargs:dictionary参数

 

线程特定数据

简而言之,线程特定数据就是线程独自持有的全局变量,相互之间的修改不会造成影响。

threading模块中使用local()方法生成一个线程独立对象,举例如下,其中sleep(1)是为了保证让子线程先运行完再运行接下来的语句。

data = threading.local()
def threadFunction():
global data
data.x = 3
print threading.currentThread(), data.x

if __name__ == '__main__':
data.x = 1
tFunc = threading.Thread(target = threadFunction).start();
time.sleep(1)
print threading.current_thread(), data.x

 

输出如下,可以看到,Thread-1中对data.x的修改并没有影响到主线程中data.x的值。

<Thread(Thread-1, started 36208)> 3
<_MainThread(MainThread, started 35888)> 1


互斥锁

threading中定义了两种锁:threading.Lock和threading.RLock。两者的不同在于后者是可重入锁,也就是说在一个线程内重复LOCK同一个锁不会发生死锁,这与POSIX中的PTHREAD_MUTEX_RECURSIVE也就是可递归锁的概念是相同的。

关于互斥锁的API很简单,只有三个函数————分配锁,上锁,解锁。

threading.Lock()        分配一个互斥锁
acquire([blocking=1])   上锁(阻塞或者非阻塞,非阻塞时相当于try_lock,通过返回False表示已经被其它线程锁住。)
release()               解锁

 

条件变量

条件变量总是与互斥锁一起使用的,threading中的条件变量默认绑定了一个RLock,也可以在初始化条件变量的时候传进去一个自己定义的锁。

可用的函数如下

threading.Condition([lock])  分配一个条件变量
acquire(*args)               条件变量上锁
release()                    条件变量解锁
wait([timeout])              等待唤醒,timeout表示超时
notify(n=1)                  唤醒最大n个等待的线程
notifyAll()、notify_all()    唤醒所有等待的线程

 

下面这个例子使用条件变量来控制两个线程交替运行

num = 0
def threadFunction(arg):
global num
while num < 10:
cond.acquire()
while num % 2 != arg:
cond.wait()
print 'Thread %d - %d' %(arg, num)
num += 1
cond.notify()
cond.release()

if __name__ == '__main__':
cond = threading.Condition()
threading.Thread(target = threadFunction, args=(0,)).start();
threading.Thread(target = threadFunction, args=(1,)).start();

 

Thread类还定义了以下常用方法与属性:

Thread.getName() 
Thread.setName()
Thread.name

  用于获取和设置线程的名称。

Thread.ident

  获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。

Thread.is_alive() 
Thread.isAlive()

  判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。

Thread.join([timeout])

  调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。

threading.RLock和threading.Lock

  在threading模块中,定义两种类型的琐:threading.Lock和threading.RLock。它们之间有一点细微的区别,通过比较下面两段代码来说明:

 

[python] view plaincopy
 
  1. import threading  
  2. lock = threading.Lock() #Lock对象  
  3. lock.acquire()  
  4. lock.acquire()  #产生了死琐。  
  5. lock.release()  
  6. lock.release()  

 

 

[python] view plaincopy
 
  1. import threading  
  2. rLock = threading.RLock()  #RLock对象  
  3. rLock.acquire()  
  4. rLock.acquire() #在同一线程内,程序不会堵塞。  
  5. rLock.release()  
  6. rLock.release()  


  这两种琐的主要区别是:RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。注意:如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。

 

threading.Condition

  可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):

Condition.wait([timeout]):  

  wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。

Condition.notify():

  唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。

Condition.notify_all() 
Condition.notifyAll()

  唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。

threading.Event

  Event实现与Condition类似的功能,不过比Condition简单一点。它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。)

Event.wait([timeout])

  堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。

Event.set()

  将标识位设为Ture

Event.clear()

  将标识伴设为False。

Event.isSet()

  判断标识位是否为Ture。