1

python threading模块

 2 years ago
source link: https://www.hi-roy.com/posts/python-threading%E6%A8%A1%E5%9D%97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python threading模块

2013-11-13

threading模块

  1. Thread 线程类,这是我们用的最多的一个类,你可以指定线程函数执行或者继承自它都可以实现子线程功能;
  2. Timer与Thread类似,但要等待一段时间后才开始运行;
  3. Lock 锁原语,这个我们可以对全局变量互斥时使用;
  4. RLock 可重入锁,使单线程可以再次获得已经获得的锁;
  5. Condition 条件变量,能让一个线程停下来,等待其他线程满足某个“条件”;
  6. Event 通用的条件变量。多个线程可以等待某个事件发生,在事件发生后,所有的线程都被激活;
  7. Semaphore为等待锁的线程提供一个类似“等候室”的结构;
  8. BoundedSemaphore 与semaphore类似,但不允许超过初始值;

Thread类

  1. 是你主要的线程类,可以创建进程实例。该类提供的函数包括:
  2. getName(self) 返回线程的名字
  3. isAlive(self) 布尔标志,表示这个线程是否还在运行中
  4. isDaemon(self) 返回线程的daemon标志
  5. join(self, timeout=None) 程序挂起,直到线程结束,如果给出timeout,则最多阻塞timeout秒
  6. run(self) 定义线程的功能函数
  7. setDaemon(self, daemonic) 把线程的daemon标志设为daemonic
  8. setName(self, name) 设置线程的名字
  9. start(self) 开始线程执行

关于join()和setDaemon

join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。

setDaemon:主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。

举个例子如下:

#coding=utf-8
import threading
import time
class myThread(threading.Thread):
    def __init__(self, threadname):
        threading.Thread.__init__(self, name=threadname)
        self.st = 5
    def run(self):
        time.sleep(self.st)
        print "@@@"+self.getName()
    def setSt(self, t):
        self.st = t
def fun1():
    t1.start()
    #t1.join()  如果有这句,则程序先等待5秒后才会输出t1,fun1 done...等语句
    print "fun1 done"
def fun2():
    t2.start()
    print "fun2 done"
t1=myThread("t1")
t2=myThread("t2")
t2.setSt(10);
#t1.setDaemon(True)
t2.setDaemon(True)  #如果有这句话,则 now u will..后只会输出t1了,因为fun2执行完毕后直接结束掉了t2
fun1()
fun2()
print "now u will see me"

 Timer 类

与Thread相似,只是它要等待一段时间后才开始运行。

  1. activeCount()      返回活动的线程对象的数量
  2. currentThread()   返回当前线程对象
  3. enumerate()         返回当前活动线程的列表
  4. settrace(func)             为所有线程设置一个跟踪函数
  5. setprofile(func)    为所有线程设置一个profile函数

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK