• 【Python】多线程-3


    #练习:线程等待 Event e.set() e.wait()
     
    from threading import Thread, Lock
    import threading
    import time
     
    def wait_for_event(e):
        #Wait for the event to be set before doing anything
        print 'wait_for_event: starting'
        e.wait() # 等待收到能执行信号,如果一直未收到将一直阻塞
        print 'wait_for_event: e.is_set()->', e.is_set()
     
    def wait_for_event_timeout(e, t):
        #Wait t seconds and then timeout
        print 'wait_for_event_timeout: starting'
        e.wait(t)# 等待t秒超时,此时Event的状态仍未未设置
        print 'wait_for_event_timeout: e.is_set()->', e.is_set()
        e.set()# 设置Event的状态
     
    if __name__ == '__main__':
        e = threading.Event()
        print "begin, e.is_set()", e.is_set()
        w1 = Thread(name = 'block', target = wait_for_event, args = (e,))
        w1.start()
     
        w2 = Thread(name = 'nonblock', target = wait_for_event_timeout, args = (e, 2))
        w2.start()
        print 'main: waiting before calling Event.set()'
        time.sleep(3)
        # e.set()
        print 'main: event is set'
     
     
    #练习:condition 等待notify_all() notify()
    import threading as tr
    import time
    def consumer(cond):
        with cond:
            print("consumer before wait")
            cond.wait() # 等待消费
            print("consumer after wait")
     
    def producer(cond):
        with cond:
            print("producer before notifyAll")
            cond.notify_all() # 通知消费者可以消费了
            print("producer after notifyAll")
     
    if __name__ == '__main__':   
        condition = tr.Condition()
     
        t1 = tr.Thread(name = "thread-1", target = consumer, args=(condition,))
        t2 = tr.Thread(name = "thread-2", target = consumer, args=(condition,))
        t3 = tr.Thread(name = "thread-3", target = producer, args=(condition,))
     
        t1.start()
        time.sleep(2)
        t2.start()
        time.sleep(2)
        t3.start()
     
     
     
    #练习:线程队列 队列是一种数据结构
    from threading import Thread
    from Queue import Queue  
    import random, time
     
    # 储钱罐
    def create(queue):  
        for i in [100, 50, 20, 10, 5, 1, 0.5]:
          if not queue.full():
            queue.put(i)  # 入队列
            print 'Put %sRMB to queue.' %i
            time.sleep(1)
     
    # 取储钱罐中的零钱花
    def get(queue):
      while 1:
        if not queue.empty():
          print 'Get %sRMB from queue.' %queue.get()
          time.sleep(2)
        else:
          break 
     
    if __name__=="__main__":
        q = Queue() # 创建一个队列实例
        create_t = Thread(target = create, args = (q,))  
        get_t = Thread(target = get, args = (q,))  
        create_t.start() 
        #time.sleep(1) #这里稳妥起见,最好是sleep1秒
        get_t.start()
        create_t.join()
        get_t.join()
     
     
    #练习:死锁 互相等,结果谁也等不到谁
     
    import threading  
    import time
     
    #声明全局锁 不用global直接用
    lock1 = threading.Lock()  
    lock2 = threading.Lock()  
    print lock1, lock2
    class T1(threading.Thread):  
        def __init__(self, name):  
            threading.Thread.__init__(self)  
            self.t_name = name  
     
        def run(self):  
            lock1.acquire()  
            time.sleep(1)#睡眠的目的是让线程2获得调度,得到第二把锁
            print 'in thread T1',self.t_name
            time.sleep(2) 
            lock2.acquire() #线程1请求第二把锁
            print 'in lock l2 of T1'  
            lock2.release()      
            lock1.release() 
     
    class T2(threading.Thread):  
        def __init__(self, name):  
            threading.Thread.__init__(self)  
            self.t_name = name  
     
        def run(self):  
            lock2.acquire()  
            time.sleep(2)#睡眠的目的是让线程1获得调度,得到第一把锁
            print 'in thread T2',self.t_name
            lock1.acquire() #线程2请求第一把锁
            print 'in lock l1 of T2'
            lock1.release() 
            lock2.release() 
     
    def test():  
        thread1 = T1('A')  
        thread2 = T2('B')  
        thread1.start()  
        thread2.start()  
     
    if __name__== '__main__':  
        test()
  • 相关阅读:
    hdu5360 Hiking(水题)
    hdu5348 MZL's endless loop(欧拉回路)
    hdu5351 MZL's Border(规律题,java)
    hdu5347 MZL's chemistry(打表)
    hdu5344 MZL's xor(水题)
    hdu5338 ZZX and Permutations(贪心、线段树)
    hdu 5325 Crazy Bobo (树形dp)
    hdu5323 Solve this interesting problem(爆搜)
    hdu5322 Hope(dp)
    Lightoj1009 Back to Underworld(带权并查集)
  • 原文地址:https://www.cnblogs.com/jingsheng99/p/8859163.html
Copyright © 2020-2023  润新知