pythonthread锁对象



#!/usr/bin/env python


import thread

from time import sleep, ctime


loops = [4,2]


def loop(nloop, nsec, lock):

print 'start loop', nloop, 'at:', ctime()打印开始nloop 创建时间

sleep(nsec)休眠时间

print 'loop', nloop, 'done at:', ctime()打印结束nloop 创建时间

lock.release()释放lock锁


def main():定义main()函数

print 'starting at:', ctime()打印开始 创建时间

locks = []定义locks列表

nloops = range(len(loops))nloops = [0, 1]


for i in nloops:循环nloops

lock = thread.allocate_lock()定义lock = 分配一个LockType 类型的锁对象

lock.acquire()获取lock 尝试获取锁对象

locks.append(lock)把获取的lock放到locks列表里面


for i in nloops:

thread.start_new_thread(loop, (i, loops[i], locks[i]))通过函数loop创建线程,分别传0 4 locks[0],然后执行


for i in nloops:循环nloops

while locks[i].locked(): pass如果获取了锁对象 执行站位


print 'all DONE at:', ctime()打印all done at 创建时间


if __name__ == '__main__':

main()





[root@localhost python]# ./mtsleep2.py

starting at: Sun Sep 15 07:17:04 2013

start loop 1 at: Sun Sep 15 07:17:04 2013

start loop 0 at: Sun Sep 15 07:17:04 2013

loop 1 done at: Sun Sep 15 07:17:06 2013

loop 0 done at: Sun Sep 15 07:17:08 2013

all DONE at: Sun Sep 15 07:17:08 2013


你可能感兴趣的:(thread,python,threading,锁对象)