def get_time(): return time.strftime("%Y-%m-%d %H:%M:%S") def show_start_info(tname): print '%s start at: %s' %(tname, get_time()) def show_acquire_info(tname): print '%s acquire at: %s' % (tname, time.time()) def show_add_once_res(tname): print '%s add: %s at: %s' % (tname, share_data, time.time()) def show_end_info(tname): print 'End %s with: %s at: %s' % (tname, share_data, time.time()) def show_wait_info(tname): print '%s wait at: %s' % (tname, time.time())
条件变量可以使线程已经获得锁的情况下,在条件不满足的时候可以主动的放弃锁,通知唤醒其他阻塞的线程;基本工作过程如下:
创建一个全局条件变量对象;
每一个线程执行前先acquire条件变量,获取则执行,否则阻塞。
当前执行线程推进过程中会判断一些条件,如果条件不满足则wait并主动释放锁,调用wait会使当前线程阻塞;
判断条件满足,进行一些处理改变条件后,当前线程通过notify方法通知并唤醒其他线程,其他处于wait状态的线程接到通知后会重新判断条件,若满足其执行条件就执行。注意调用notify不会释放锁;
不断的重复这一过程,直到任务完成。
这里有一点不好理解,当前线程修改了条件之后,通过notify通知其他线程检查其各自的执行条件是否满足,但是条件变量持有的唯一的锁被当前线程拥有而且没有释放,那么其他线程怎么执行?
Python文档给出的说明如下:
Note: an awakened thread does not actually return from its wait() call until it can reacquire the lock. Since notify() does not release the lock, its caller should.