python 多线程编程的例子

发布时间:2020-11-30编辑:脚本学堂
本文介绍下,用python实现多线程编程的一个例子,有需要的朋友参考下,希望对大家有所帮助。

python 多线程编程示例:
 

复制代码 代码示例:
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( 函数名,参数),即使不带入参数,也要使用" () "带入参数表。

通过以上几个小例子,大家可以了解下python中多线程编程的方法,祝大家学习进步。