美文网首页python学习资料
python 实现多线程编程

python 实现多线程编程

作者: _String_ | 来源:发表于2017-05-19 00:49 被阅读0次

    什么是进程?

    进程是二进制可执行文件的数据,他们只有被调到内存中,被操作系统调用的时候才开始他们的生命周期,进程是程序的每一次执行,进程有单独的内存空间、数据栈等,所以只能使用进程间通信(IPC),而不能直接共享信息。

    什么是线程?

    线程又称轻量级进程,所有线程运行在同一进程中,共享相同的运行环境。一个进程中各线程的数据是共享的。
    在python中使用thread模块实现多读线程操作。
    倒入thread模块import thread
    如果没有使用线程,系统执行任务是顺序的,一个执行完后才会去执行另一个,我们通过sleep函数验证cpu等待任务过程。
    示例代码如下:
    `` #!/usr/bin/env python
    from time import sleep, ctime

    def loop0():
    print 'start loop0 at:', ctime()
    sleep(4)
    print 'loop0 done at:', ctime()

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

    def main():
    print 'string at :', ctime()
    loop0()
    loop1()
    print 'all done at:', ctime()

    if name == 'main':
    main()
    ``
    运行结果如图:

    image.png

    python的threading模块

    python提供了几个线程模块,包括thread、threading、queue等。thread和threading允许程序员创建和管理线程,thread提供基本线程和锁支持,threading提供更高级的线程管理。queue允许用户创建一个可以用于多个线程之间个共享数据的数据结构。
    使用thread创建线程示例代码如下:
    ``

    !/usr/bin/env python

    import thread
    from time import ctime, sleep

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

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

    def main():
    print 'starting at:', ctime()
    thread.start_new_thread(loop0,())
    thread.start_new_thread(loop1,())
    sleep(6)
    print 'all done at:', ctime()

    if name == 'main':
    main()
    ``
    运行结果如图:

    image.png

    相关文章

      网友评论

        本文标题:python 实现多线程编程

        本文链接:https://www.haomeiwen.com/subject/eseexxtx.html