Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1644909
  • 博文数量: 245
  • 博客积分: 10378
  • 博客等级: 上将
  • 技术积分: 2571
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-27 08:19
文章分类

全部博文(245)

文章存档

2013年(4)

2012年(8)

2011年(13)

2010年(68)

2009年(152)

分类: Python/Ruby

2010-11-13 19:28:04

from time import sleep,ctime
>>> def loop0():
    print( 'start loop 0 at:',ctime() )
    sleep(4)
    print( 'loop0 done at :',ctime())

    
>>> def loop1():
    print('start loop 1 at :',ctime())
    sleep(2)
    print('loop1 done at:',ctime())

    
>>> def main():
    print( 'start main at:',ctime())
    loop0()
    loop1()
    print( 'All DONE at:',ctime() )

    
>>> if __name__ == '__main__':
    main()

没有线程的代码。

('start main at:', 'Sat Nov 13 19:09:58 2010')
('start loop 0 at:', 'Sat Nov 13 19:09:58 2010')
('loop0 done at :', 'Sat Nov 13 19:10:02 2010')
('start loop 1 at :', 'Sat Nov 13 19:10:02 2010')
('loop1 done at:', 'Sat Nov 13 19:10:04 2010')
('All DONE at:', 'Sat Nov 13 19:10:04 2010')

带入了现成:

from time import sleep,ctime
>>> def loop0():
    print( 'start loop 0 at:',ctime() )
    sleep(4)
    print( 'loop0 done at :',ctime())

    
>>> def loop1():
    print('start loop 1 at :',ctime())
    sleep(2)
    print('loop1 done at:',ctime())

>>> def main():
    print( 'start main at:',ctime() )
    thread.start_new_thread( loop0, () )
    thread.start_new_thread( loop1,())
    sleep(6)
    print( 'all DONE at:',ctime() )

运行结果:

('start main at:', 'Sat Nov 13 19:14:30 2010')
('start loop 0 at:', 'Sat Nov 13 19:14:30 2010')
('start loop 1 at :', 'Sat Nov 13 19:14:30 2010')
('loop1 done at:', 'Sat Nov 13 19:14:32 2010')
('loop0 done at :', 'Sat Nov 13 19:14:34 2010')
('all DONE at:', 'Sat Nov 13 19:14:36 2010')

创建多线程的函数: thread.start_new_thread

需要的模块; import thread  

start_new_thread(...)
        start_new_thread(function, args[, kwargs])
        (start_new() is an obsolete synonym)
        
        Start a new thread and return its identifier. The thread will call the
        function with positional arguments from the tuple args and keyword arguments
        taken from the optional dictionary kwargs. The thread exits when the
        function returns; the return value is ignored. The thread will also exit
        when the function raises an unhandled exception; a stack trace will be
        printed unless the exception is SystemExit.


start_new_thread( 函数名,参数),即使不带入参数,也要带入参数表,可以使用" () "

 

阅读(1089) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~