zoukankan      html  css  js  c++  java
  • python 多线程

    例一:不使用多线程

    #-*-coding:utf-8-*-
    #compare for multi threadsafety
    import time
    
    def worker():
        print "worker"
        time.sleep(1)
        return
    if __name__=="__main__":
        for i in xrange(5):
            worker()

    例二:使用多线程

    #-*-coding:utf-8-*-
    import threading
    import time
     
    def worker():
        print "worker"
        time.sleep(1)
        return
     
    for i in xrange(5):
        t=threading.Thread(target=worker)
        t.start()

    例三:返回线程和主线程

    #-*-coding:utf-8-*-
    import threading
    import time
     
    def worker():
        print "worker"
        time.sleep(1)
        return
     
    for i in xrange(5):
        t=threading.Thread(target=worker)
        t.start()
    print "current has %d threads" % (threading.activeCount() - 1)

    例四:threading.enumerate()的使用。此方法返回当前运行中的Thread对象列表

    #!/usr/bin/python
    #test the variable threading.enumerate()
    import threading
    import time
     
    def worker():
        print "test"
        time.sleep(2)
     
    threads = []
    for i in xrange(5):
        t = threading.Thread(target=worker)
        threads.append(t)
        t.start()
     
    for item in threading.enumerate():
        print item
     
    print
     
    for item in threads:
        print item


    例五:threading.setDaemon()的使用。设置后台进程。

  • 相关阅读:
    Promise/Deferred
    理解RESTful架构
    XSS跨站脚本攻击
    crsf 跨站请求伪造
    街头生意
    什么是开光
    影响力
    linux上安装rar解压软件
    sip协议音视频性能测试
    解决关键SSL安全问题和漏洞
  • 原文地址:https://www.cnblogs.com/bluewelkin/p/4329169.html
Copyright © 2011-2022 走看看