zoukankan      html  css  js  c++  java
  • 信号量、event事件和线程queue

    from threading import Thread,Semaphore
    import time,random
    sm=Semaphore(5)
    
    def task(name):
        sm.acquire()
        print('%s 正在上厕所' %name)
        time.sleep(random.randint(1,3))
        sm.release()
    
    if __name__ == '__main__':
        for i in range(20):
            t=Thread(target=task,args=('路人%s' %i,))
            t.start()
    View Code
    from threading import Thread,Event
    import time
    
    event=Event()
    
    def light():
        print('红灯正亮着')
        time.sleep(3)
        event.set() #绿灯亮
    
    def car(name):
        print('车%s正在等绿灯' %name)
        event.wait() #等灯绿
        print('车%s通行' %name)
    
    if __name__ == '__main__':
        # 红绿灯
        t1=Thread(target=light)
        t1.start()
        #
        for i in range(10):
            t=Thread(target=car,args=(i,))
            t.start()
    View Code
    import queue
    
    # queue.Queue() #先进先出
    # q=queue.Queue(3)
    # q.put(1)
    # q.put(2)
    # q.put(3)
    # print(q.get())
    # print(q.get())
    # print(q.get())
    
    # queue.LifoQueue() #后进先出->堆栈
    # q=queue.LifoQueue(3)
    # q.put(1)
    # q.put(2)
    # q.put(3)
    # print(q.get())
    # print(q.get())
    # print(q.get())
    # queue.PriorityQueue() #优先级
    q=queue.PriorityQueue(3) #优先级,优先级用数字表示,数字越小优先级越高
    q.put((10,'a'))
    q.put((-1,'b'))
    q.put((100,'c'))
    print(q.get())
    print(q.get())
    print(q.get())
    View Code
  • 相关阅读:
    Go语言基础之map
    Go语言基础之切片
    Go语言基础之数组
    Go语言fmt.Printf使用指南
    Go语言基础之流程控制
    Go语言基础之运算符
    Go语言基础之变量和常量
    Go语言环境搭建
    随笔
    使用SocketServer 创建TCP服务端
  • 原文地址:https://www.cnblogs.com/xuqidong/p/13648849.html
Copyright © 2011-2022 走看看