Python threading test
''' Created on Mar 24, 2013 @author: benjamin ''' import threading, time class Boy(threading.Thread): def __init__(self, cond, name): super(Boy, self).__init__() self.__cond = cond self.__name = name def run(self): # Acquire the underlying lock. self.__cond.acquire() print("{}".format(self.__name +': Marry me?')) # wake up one thread waiting on this condition self.__cond.notify() # Wait until notified or until a timeout occurs. self.__cond.wait() print("{}".format(self.__name +': Come on.')) self.__cond.notify() self.__cond.wait() print("{}".format(self.__name +': Oh yeah!')) # Release the underlying lock. self.__cond.release() class Girl(threading.Thread): def __init__(self, cond, name): super(Girl, self).__init__() self.__cond = cond self.__name = name def run(self): self.__cond.acquire() self.__cond.wait() print("{}".format(self.__name +': Let me think for a while.')) self.__cond.notify() self.__cond.wait() print("{}".format(self.__name +': All right.')) self.__cond.notify() self.__cond.release() def _ConditionTest(): print("Condition Thread Testing...") cond = threading.Condition() boy = Boy(cond, 'LiLei') girl = Girl(cond, 'HanMeiMei') girl.start() boy.start() class Man(threading.Thread): def __init__(self, event, name): super(Man, self).__init__() self.__event = event self.__name = name def run(self): # Reset the internal flag to false. self.__event.clear() print("{}".format(self.__name +': Marry me?')) # Set the internal flag to true. # All threads waiting for it to become true are awakened. # Threads that call wait() once the flag is true will not block at all. self.__event.set() time.sleep(0.5) # Block until the internal flag is true. self.__event.wait() self.__event.clear() print("{}".format(self.__name +': Come on.')) self.__event.set() time.sleep(0.5) self.__event.wait() self.__event.clear() print("{}".format(self.__name +': Oh yeah!')) class Woman(threading.Thread): def __init__(self, event, name): super(Woman, self).__init__() self.__event = event self.__name = name def run(self): self.__event.wait() self.__event.clear() print("{}".format(self.__name +': Let me think for a while.')) # Reset the internal flag to false. self.__event.set() time.sleep(0.5) self.__event.wait() self.__event.clear() print("{}".format(self.__name +': All right.')) self.__event.set() def _EventTest(): print("Event Thread Testing...") event = threading.Event() boy = Man(event, 'Jack') girl = Woman(event, 'Rose') girl.start() boy.start() if __name__ == '__main__': lock_obj = threading.Lock() with lock_obj: _ConditionTest() print("") with lock_obj: _EventTest()
Reference:
1. http://docs.python.org/2/library/threading.html
2. http://www.cnblogs.com/twelfthing/articles/2095502.html
浙公网安备 33010602011771号