文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Python_多线程编程

Python_多线程编程

时间:2010-11-13  来源:tastesweet

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( 函数名,参数),即使不带入参数,也要带入参数表,可以使用" () "

 

相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载