python 多线程之thread.start_new_thread

python支持跨平台的多线程

创建线程的方式之一就是最基本的 thread.start_new_thread(handler,(params...))

这里给出一个在windows xp 下运行没有问题的例子(虽然到处都是):

#python 2.7
import time
import thread
def timer(i,interval):
    
while True:
        
#print 'thread timer: %d time %s'%(i,time.ctime())
        ts = 'thread: '+ str(i)+" - "+str(interval)
        
print ts        
        time.sleep(interval)
def test(times):
    
for i in range(times):
        
print i         
        thread.start_new_thread(timer,(i,(i
*2 + 1)))
        
if __name__ == '__main__':
    
print 'thread test a'
    test(
5)
    time.sleep(
20)
    
print 'main thread exit...\n'

 这里要说明一点

   如果你不加

    time.sleep(20) 这行代码的话, 以上程序会报错(或者线程无法执行):

      

    Unhandled exception in thread started by
    sys.excepthook is missing
    lost sys.stderr

    因为线程管理程序找不到 timer方法(函数)的引用

    我在网上看到类似教程或文章的时候 很多是没有这一行的,不知道用意何在?

 

posted @ 2011-06-23 10:17  vily_雷  阅读(15050)  评论(8编辑  收藏  举报