python中threading的高级函数应用解析 Lock Rlock Condition Semaphore Timer Event Semaphore对象

继上一篇threading高级应用讲述了thread对象的使用,此篇将要讲述Lock Rlock Condition Semaphore Timer Event Semaphore对象的使用方法。

Lock对象
原锁是一个同步原语,当它锁住时不归某个特定的线程所有。在Python中,它是目前可用的最底层的同步原语,直接通过thread的扩展模块实现。

一个原锁处于“locked”或者“unlocked”状态中的一种。它创建时处于unlocked状态。它有两个基本的方法,acquire()和release()。当状态是unlocked时,acquire()改变该状态为locked并立即返回。当状态是locked时,acquire()将阻塞直至在另外一个线程中调用release()来将它变为unlocked,然后acquire()调用将它重置为locked并返回。release()方法应该只在locked状态下调用;它改变状态为unlocked并立即返回。如果尝试是否一个unlocked的锁,将引发一个ThreadError。

当多个线程由于acquire()等待状态变为unblocked时阻塞,当一个release()调用重置状态为unblocked时,只有一个线程能够继续;具体哪一个等待的线程能够继续没有定义,不同的实现可能不同。

所有方法的执行都是原子的。

Lock.acquire([blocking])
获取一把锁,阻塞的或者非阻塞的。

当调用时blocking参数设置为True(默认值),将阻塞直至锁变成unblocked,然后设置它的状态为locked并返回True。

当调用时blocking参数设置为False,将不会阻塞。If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True.

Lock.release()
释放一把锁。

当锁是locked时,重置它为unlocked,然后返回。如果其它任何线程正在阻塞等待锁变成unblocked,将只允许它们中一个继续。

在一把没有锁住的锁上调用时,引发一个ThreadError 。
没有返回值。

RLock对象:
一个可重入所示一个同步原语,它可以被相同的线程获得多次。Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.

To lock the lock, a thread calls its acquire() method; this returns once the thread owns the lock. To unlock the lock, a thread calls its release() method. acquire()/release() call pairs may be nested; only the final release() (the release() of the outermost pair) resets the lock to unlocked and allows another thread blocked in acquire() to proceed.

RLock.acquire([blocking=1])
Acquire a lock, blocking or non-blocking.

When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case.

When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true.

When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true.

RLock.release()
Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread.

Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked.
There is no return value.

Timer对象
这个类表示一个动作应该在一个特定的时间之后运行 — 也就是一个计时器。Timer是Thread的子类, as such also functions as an example of creating custom threads.

Timers通过调用它们的start()方法作为线程启动。timer可以通过调用cancel()方法(在它的动作开始之前)停止。timer在执行它的动作之前等待的时间间隔可能与用户指定的时间间隔不完全相同。

例如:

def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed

class threading.Timer(interval, function, args=[], kwargs={})
创建一个timer,在interval秒过去之后,它将以参数args和关键字参数kwargs运行function 。

cancel()
停止timer,并取消timer动作的执行。这只在timer仍然处于等待阶段时才工作。

Condition对象
一个条件变量总是与许多锁相关联的。多用在多个条件变量必须共同享用同一个锁的时候。
条件变量有acquire() 和release()方法,是用来调用相关锁的相应方法。它也有wait(),notify() 和notifyAll(),这三种方法只有当当前线程请求了lock对象 才会被调用,否则会触发RuntimeError异常。

wait()方法调用后 释放当前锁,然后阻塞直到被notify() 或者是 notifyAll()方法调用在其它线程中的同一个条件对象时候才会被唤醒。一旦被唤醒,就会重新获得锁并返回。也可能会产生超时。

notify()方法会唤醒正在等待条件变量的线程中的一个,前提是有线程正在等待。notifyAll()方法顾名思义就是唤醒所有正在等待条件变量的线程。
注意:
notify() 和notifyAll()方法不会释放lock对象,这就意味着醒着的线程或者多个线程将不会立刻从它们的wait()调用中终止。只有当线程调用notify()或notifyall()最后放弃锁持有的锁时才会被唤醒。
例子:

cv.acquire()
while not an_item_is_available():
    cv.wait()
get_an_available_item()
cv.release()

# Produce one item
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()

Event对象
事件对象是线程间最简单的通信机制之一:线程可以激活在一个事件对象上等待的其他线程

每个事件对象管理一个内部标志,可以在事件对象上调用set() 方法将内部标志设为true,调用 clear() 方法将内部标志重置为flase。在事件对象调用 wait() 方法时,线程将阻塞直到事件对象的内部标志被设为true。
threading.Event类
内部flag参数,原始值为false
is_set()
isSet()
只有当flag为true的时候返回为true

set()
Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.

clear()
Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

wait([timeout])
Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out.

你可能感兴趣的:(python)