• 技术文章 >Python技术 >Python高级

    Python中的threading模块是什么

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-06-29 15:01:22原创2710

    threading提供了一个比thread模块更高层的API来提供线程的并发性。这些线程并发运行并共享内存。

    下面来看threading模块的具体用法:

    一、Thread的使用,目标函数可以实例化一个Thread对象,每个Thread对象代表着一个线程,可以通过start()方法,开始运行。

    这里对使用多线程并发,和不适用多线程并发做了一个比较:

    首先是不使用多线程的操作:

    代码如下:

    #!/usr/bin/python
    #compare for multi threads
    import time
     
    def worker():
        print "worker"
        time.sleep(1)
        return
     
    if __name__ == "__main__":
        for i in xrange(5):
            worker()

    执行结果如下:

    下面是使用多线程并发的操作:

    代码如下:

    #!/usr/bin/python
    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.activeCount()的使用,此方法返回当前进程中线程的个数。返回的个数中包含主线程。

    代码如下:

    #!/usr/bin/python
    #current's number of threads
    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)

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

    相关推荐:《Python视频教程

    代码如下:

    #!/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()的使用。设置后台进程。

    代码如下:

    #!/usr/bin/python
    #create a daemon
    import threading
    import time
     
    def worker():
        time.sleep(3)
        print "worker"
     
    t=threading.Thread(target=worker)
    t.setDaemon(True)
    t.start()
    print "haha"

    可以看出worker()方法中的打印操作并没有显示出来,说明已经成为后台进程。

    threading.Thread

    Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入。下面分别举例说明。先来看看通过继承threading.Thread类来创建线程的例子:

    #coding=gbk
    import threading, time, random
    count = 0
    class Counter(threading.Thread):
      def __init__(self, lock, threadName):
         
    '''@summary: 初始化对象。
          
         
    @param lock: 琐对象。
         
    @param threadName: 线程名称。
         
    '''
        super(Counter, self).__init__(name = threadName)
    #注意:一定要显式的调用父类的初始
    化函数。
        self.lock = lock
        
      def run(self):
         
    '''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
         
    '''
        global count
        self.lock.acquire()
        for i in xrange(10000):
          count = count + 1
        self.lock.release()
    lock = threading.Lock()
    for i in range(5):
      Counter(lock, "thread-" + str(i)).start()
    time.sleep(2) 
    #确保线程都执行完毕
    print count

    在代码中,我们创建了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是锁对象,另一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增加10000。在接下来的代码中,创建了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);start()方法用于启动线程。

    专题推荐:python threading
    品易云
    上一篇:Python中fock()函数如何使用 下一篇:Python中Thread子类如何封装

    相关文章推荐

    • Python中的协程是什么• Python中fock()函数如何使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网