zoukankan      html  css  js  c++  java
  • threading模块小结

    这篇文章是别人文章的一个观后小结,不是什么原创。

    首先第一个例子:

    import threading
    import time
    def worker():
        print "worker"
        time.sleep(1)
        return
    for i in xrange(5):
        t = threading.Thread(target=worker)
        t.start()
     
    倒数第二行就是对threading模块简单的实例化一下,生成一个名为t的对象,然后调用start方法执行。非常简单
     
     
    第二个例子:
    import threading
    import time
    def worker():
        print "test"
        time.sleep(1)
    for i in xrange(5):
        t = threading.Thread(target=worker)
        t.start()
    print "current has %d threads" % (threading.activeCount() - 1)
     
    activeCount方法会返回threading对象的激活线程数。
     
     
    第三个例子:
    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
    for item in threads:
        print item
     
    enumeration方法会枚举threading对象的全部线程
     
     
    第四个例子:
    import threading
    import time
      
    def worker():
        time.sleep(3)
        print "worker"
      
    t=threading.Thread(target=worker)
    t.setDaemon(True)
    t.start()
    print "haha"
     
    setDaemon方法会设置后台进程。
     
    恩,以上是threading的几个常用方法,over~
     
  • 相关阅读:
    luogu_1414 又是毕业季II
    luogu_1372 又是毕业季I
    luogu_1313 计算系数
    luogu_1134 阶乘问题
    luogu_1514 引水入城
    luogu_1120 小木棍
    文件操作
    快速排序
    c oth
    ANSI C与C89、C99、C11区别差异
  • 原文地址:https://www.cnblogs.com/hksac/p/5260768.html
Copyright © 2011-2022 走看看