Thread类定义了以下常用方法与属性:

  • Thread.getName() \Thread.setName():老方式用于获取和设置线程的名称,官方建议用Thread.name替代
  • Thread.ident:获取线程的标识符。只有在调用start()方法执行后才有效,否则返回None。
  • Thread.is_alive():判断线程是否是激活的。
  • Thread.join([timeout]):调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。

另一个较高级的锁为RLock锁,RLock对象内部维护着一个Lock对象,它是一种可重入的对象。对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么由于第一次acquire之后没有release,第二次acquire将挂起线程。这会导致Lock对象永远不会release,使得线程死锁。RLock对象允许一个线程多次对其进行acquire操作,因为在其内部通过一个counter变量维护着线程acquire的次数。而且每一次的acquire操作必须有一个release操作与之对应,在所有的release操作完成之后,别的线程才能申请该RLock对象。

threading模块对Lock也提供和封装,提供了更高级的同步方式(可以理解为更高级的锁),包括threading.Event和threading.Condition,其中threading.Event为提供了简单的同步方式:一个进程标记event,其他进程等待,只需下面的几个方法即可:

  • Event.wait([timeout]):堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。
  • Event.set():将标识号设为True。
  • Event.clear():设为标识符False。

threading.Condition可以把Condition理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):

  • Condition.wait([timeout]):wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。
  • Condition.notify():唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。
  • Condition.notify_all():唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
from time import ctime,sleep

lock = threading.Lock()
#define a global variable
some_var = 0


#########################
###simple mutilThread begin
#########################
def music(func):
    for i in range(2):
        print ("I was listening to %s. %s" %(func,ctime()))
        sleep(1)

def move(func):
    for i in range(2):
        print ("I was at the %s! %s" %(func,ctime()))
        sleep(2)

threads = []
t1 = threading.Thread(target=music,args=('爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('阿凡达',))
threads.append(t2)
#########################
###simple mutilThread end
#########################

#########################
###MutilThread Lock begin
#########################
class IncrementThread(threading.Thread):
    def run(self):
        #we want to read a global variable
        #and then increment it
        global some_var
        lock.acquire()
        read_value = some_var
        print ("some_var in %s is %d" % (self.name, read_value))
        some_var = read_value + 1
        print ("some_var in %s after increment is %d" % (self.name, some_var))
        lock.release()
  
def use_increment_thread():
    threads = []
    for i in range(50):
        t = IncrementThread()
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
    print ("After 50 modifications, some_var should have become 50")
    print ("After 50 modifications, some_var is %d" % (some_var))
#########################
###MutilThread Lock end
#########################


if __name__ == '__main__':
    
#########################
###call simple mutilThread
#########################
    for t in threads:
        t.setDaemon(True)
        t.start()

    for t in threads:
        t.join()

    print ("all over %s" %(ctime()))

#########################
###call MutilThread Lock
#########################
    # use_increment_thread()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
from time import ctime,sleep

lock = threading.Lock()
#define a global variable
some_var = 0


#########################
###simple mutilThread begin
#########################
def music(func):
    for i in range(2):
        print ("I was listening to %s. %s" %(func,ctime()))
        sleep(1)

def move(func):
    for i in range(2):
        print ("I was at the %s! %s" %(func,ctime()))
        sleep(2)

threads = []
t1 = threading.Thread(target=music,args=('爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('阿凡达',))
threads.append(t2)
#########################
###simple mutilThread end
#########################

#########################
###MutilThread Lock begin
#########################
class IncrementThread(threading.Thread):
    def run(self):
        #we want to read a global variable
        #and then increment it
        global some_var
        lock.acquire()
        read_value = some_var
        print ("some_var in %s is %d" % (self.name, read_value))
        some_var = read_value + 1
        print ("some_var in %s after increment is %d" % (self.name, some_var))
        lock.release()
  
def use_increment_thread():
    threads = []
    for i in range(50):
        t = IncrementThread()
        threads.append(t)
        t.start()
    for t in threads:
        t.join()
    print ("After 50 modifications, some_var should have become 50")
    print ("After 50 modifications, some_var is %d" % (some_var))
#########################
###MutilThread Lock end
#########################


if __name__ == '__main__':
    
#########################
###call simple mutilThread
#########################
    for t in threads:
        t.setDaemon(True)
        t.start()

    for t in threads:
        t.join()

    print ("all over %s" %(ctime()))

#########################
###call MutilThread Lock
#########################
    # use_increment_thread()