u012310391
kuyuzhiqi
2017-10-26 23:34

python多线程锁机制(练习题)

2
  • python
  • 多线程

代码如下:

 from atexit import register
from random import randrange
from threading import Thread, currentThread, Lock
from time import sleep, ctime


class CleanoutSet(set):
    def __str__(self):
        return ', '.join(x for x in self)

lock = Lock()
loops = []
for x in range(randrange(3, 7)):
    loops.append(randrange(2, 5))

remaining = CleanoutSet()


def loop(nsec):
    print(nsec)
    myname = currentThread().name
    lock.acquire()
    remaining.add(myname)
    print('[%s] Started %s' % (ctime(), myname))
    lock.release()
    sleep(nsec)
    lock.acquire()
    remaining.remove(myname)
    print('[%s] completed %s (%d sec)' % (ctime(), myname, nsec))
    print(' (remaining: %s) ' % (remaining or 'NONE'))
    lock.release


def _main():
    for pause in loops:
        Thread(target=loop, args=(pause,)).start()


@register
def _atexit():
    print('all Done at: ', ctime())


if __name__ == '__main__':
    _main()

运行程序,启动一个线程,然后就会卡住,运行环境是python3.6.0,求解答,谢谢

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答