Chinaunix

标题: 【python核心编程】线程和锁的问题 [打印本页]

作者: 壮乡小顽主    时间: 2012-08-15 16:45
标题: 【python核心编程】线程和锁的问题
本帖最后由 壮乡小顽主 于 2012-08-15 16:50 编辑

python核心编程书上的脚本如下:

import thread
from time import ctime, sleep

loops = [4, 2]

def loop(nloop, nsec, lock):
    print 'start loop', nloop, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()
    lock.release()


def main():
    print 'starting at:', ctime()
    locks = []
    nloops = range(len(loops))

   
    for i in nloops:
        lock = thread.allocate_lock()
        lock.acquire()
        locks.append(lock)
   
    for i in nloops:
        thread.start_new_thread(loop, (i, loops, locks))

    print 'to here 2'
    for i in nloops:
        while locks.locked():pass
   

    print 'all DONE at:', ctime()

if __name__ == '__main__':
    main()

在python2.6上运行后报错,见截图。通过打印确定问题出在thread.start_new_thread(loop, (i, loops, locks)),麻烦高手解释一下为什么,十分感谢!脚本里的[]出不来,请看截图。


作者: majiayang2012    时间: 2012-08-15 17:04
为么,我这贴了你的程序上去可以运行啊

作者: 壮乡小顽主    时间: 2012-08-15 17:09
啊?难道我的环境有问题?神奇~回复 2# majiayang2012


   
作者: majiayang2012    时间: 2012-08-15 17:11
错误上是你的环境问题吧,我这可以运行

administrator@ubuntu:~$ python test.py
starting at: Wed Aug 15 17:10:44 2012
to here 2
start loop 1 at: Wed Aug 15 17:10:44 2012
start loop 0 at: Wed Aug 15 17:10:44 2012
loop 1 done at: Wed Aug 15 17:10:46 2012
loop 0 done at: Wed Aug 15 17:10:48 2012
all DONE at: Wed Aug 15 17:10:48 2012

作者: 壮乡小顽主    时间: 2012-08-15 17:17
谢谢帮助回复 4# majiayang2012


   
作者: linux_c_py_php    时间: 2012-08-15 20:26
什么破书, 错误百出.
  1. # -*- coding:gb2312 -*-

  2. import thread
  3. from time import ctime, sleep

  4. loops = [4, 2]

  5. def loop(nloop, nsec, lock):
  6.     print 'start loop', nloop, 'at:', ctime()
  7.     sleep(nsec)
  8.     print 'loop', nloop, 'done at:', ctime()
  9.     lock.release()


  10. def main():
  11.     print 'starting at:', ctime()
  12.     locks = []
  13.     nloops = range(len(loops))

  14.    
  15.     for i in nloops:
  16.         lock = thread.allocate_lock()
  17.         lock.acquire()
  18.         locks.append(lock)
  19.    
  20.     for i in nloops:
  21.         thread.start_new_thread(loop, (i, 5, locks[i]))

  22.     print 'to here 2'
  23.     for i in nloops:
  24.         while locks[i].locked():
  25.             pass

  26.     print 'all DONE at:', ctime()

  27. if __name__ == '__main__':
  28.     main()
复制代码

作者: bikong0411    时间: 2012-08-16 08:49
上面的在胡扯啊,还神马破书,有能耐你去写一本破书




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2