threading模块 补充

来源:互联网 发布:淘宝企业店铺介绍范文 编辑:程序博客网 时间:2024/06/08 10:15

一、工厂函数

  • threading.active_count()
  • threading.activecount()
    返回当前活动的Thread对象的数量。 返回的计数等于由enumerate()返回的列表的长度。

  • threading.Condition()
    工厂函数,返回一个新的条件变量对象。一个条件变量允许一个或多个线程等待,直到另外一个线程通知他们(他们指这些等待状态的线程)

  • threading.current_thread()

  • threading.currentThread()
    返回当前Thread对象。对应于调用者的线程控制。如果调用者的线程不是通过线程模块创建的,则返回具有有限功能的虚拟线程对象。

  • threading.enumerate()
    返回当前活动的Thread对象的列表。该列表包括守护线程、由current_thread()创建的虚拟线程以及主线程。排除了已经终止的线程和尚未启动的线程

  • threading.Event()
    工厂函数,返回一个新的event对象。event管理可以使用set()方法将其设置为True,使用clear()将其重设置为False,wait()方法则阻塞知道set()将其设置为True

  • threading.Lock()
    工厂函数,返回一个全新的原始锁对象。当一个线程获得锁后,后来的线程想要获得这个锁,需要等到当前线程释放锁

  • threading.RLock()
    工厂函数,获得一个可重入锁。

  • threading.Semaphore([value])
    工厂函数,返回一个新的信号量对象。

  • class threading.local

  • class threading.Timer

二、Thread类的方法

控制线程的类,这个类可以以 有限的方式安全的子类化。如果子类重写这个结构,它必须确保在对线程执行任何其他操作之前调用基类构造函数(Thread ._ init _())。

  • start()
    启动一个线程

  • run()
    表示线程的活动,即线程需要做的任务。该方法可以被子类覆写

  • join([timeout])
    等待直到线程终止。即主线程将不会继续运行,而是等待子线程全部终止后才会继续运行

  • getName()
    获取当前线程名

  • setNmae()
    设置线程名

  • isDaemon()

  • setDaemon()
    布尔值,指明这个线程是daemon线程(True)或者不是(False)。这个只能在start()调用之前才能设置否则会抛出RuntimeError异常。因为主线程不是后台线程,因此在主线程中创建的所有子线程默认值都是 False

  • is_alive()
    返回当前线程是否活着。

四、Event对象

singal = threading.Event()

4.1 对象属性

  • is_set()
    当且仅当内部表示为True时返回True。如果set()没有设定,则说明为为False。
singal = threading.Eventif not singal.is_set():      #这里没有使用set()方法设置内部标志,因此为False    singal.wait()
  • set()
    设定内部标志为True。所有线程等到它为真时,都会被唤醒。调用了wait()的线程,一旦检测到内部标志位True时,那么都不会继续阻塞了。

  • clear()
    设定内部标识为False。随后,调用wait()的线程都会被阻塞,直到调用set()将内部标志设置为True

  • wait([timeout])
    阻塞线程,知道内部标志设置为True。如果内部标志在入口时为真,则立即返回。 否则,阻塞将持续到另一个线程调用set()将标志设置为true,或直到可选超时发生才会结束。此方法在退出时返回内部标志,因此除非给出超时且操作超时,否则它将始终返回True。

举一个生产者消费者的例子,生产者生产了一个数据后,然后通知消费者去消费。

#!/usr/bin/pyhton#coding: utf-8import threadingimport timefrom random import randintdef customers(event, lists):    t = threading.current_thread()    while 1:        event.wait()        if event.is_set():            try:                int = lists.pop()                print '{0} is customed by {1}'.format(int, t.name)                event.clear()   #阻塞所有线程            except IndexError:                passdef producer(event, lists):    t = threading.current_thread()    while 1:        int = randint(1, 1000)        lists.append(int)        print '{0} is produced by {1}'.format(int, t.name)        event.set()     #唤醒其他线程        time.sleep(1)    #没有实际意义,为了结果输出时看的清楚点。def main():    threads = []    lists = []    event = threading.Event()    for name in ('customer1', 'customer2'):        thread = threading.Thread(target=customers, args=(event, lists))        threads.append(thread)        thread.start()    produce_thread = threading.Thread(target=producer, args=(event, lists))    threads.append(produce_thread)    produce_thread.start()    for thread in threads:        thread.join()if __name__ == '__main__':    main()---------------------------------------------------------------------------------------------------------[root@master server]# python event.py 677 is produced by Thread-3677 is customed by Thread-2898 is produced by Thread-3898 is customed by Thread-176 is produced by Thread-376 is customed by Thread-2831 is produced by Thread-3831 is customed by Thread-1947 is produced by Thread-3947 is customed by Thread-2259 is produced by Thread-3259 is customed by Thread-1564 is produced by Thread-3564 is customed by Thread-2746 is produced by Thread-3746 is customed by Thread-1472 is produced by Thread-3472 is customed by Thread-2^C520 is produced by Thread-3520 is customed by Thread-1

最后想讲一个自己写socket编程时碰到的一个问题。在多线程中,调用sys.exit(0) 退出的是当前线程,主线程是不会退出的,即阻塞解除前,程序不会退出。

0 0