• 27 python 初学(信号量、条件变量、同步条件、队列)


    参考博客: www.cnblogs.com/yuanchenqi/articles/5733873.html 

    semaphore 信号量:

    condition 条件变量:

    event 同步条件:条件同步和条件变量同步差不多意思,只是少了锁功能。因为条件同步设计于别访问共享资源的条件环境

    多线程利器(queue):队列本身有一把锁

    q.put(‘xiaoming’, 0)

    q.get(0)

    q.qsize()  返回队列大小

    q.empty()

    q.full()

    semaphore:

    # _author: lily
    # _date: 2019/1/29
    
    import threading , time
    
    class MyThread(threading.Thread):
        def run(self):
            if semaphore.acquire():
                print(self.name)
                time.sleep(3)
                semaphore.release()
    
    if __name__ == '__main__':
        semaphore = threading.BoundedSemaphore(5)
        thread_list = []
        for i in range(100):
            thread_list.append(MyThread())
        for i in thread_list:
            i.start()
    View Code

    condition:

    # _author: lily
    # _date: 2019/1/29
    
    import threading,time
    from random import randint
    
    class Producer(threading.Thread):
        def run(self):
            global L
            while True:
                val = randint(0, 100)
                print('Producer', self.name, ': Append', str(val), L)
                if lock_con.acquire():
                    L.append(val)
                    lock_con.notify()
                    lock_con.release()
                time.sleep(3)
    
    class Consumer(threading.Thread):
        def run(self):
            global L
            while True:
                lock_con.acquire()
                if len(L) == 0:
                    lock_con.wait()
                    print('Consumer', self.name, ': Delete', str(L[0]), L)
                    del L[0]
                    lock_con.release()
                    time.sleep(0.25)
    
    
    if __name__ == '__main__':
        L = []
        lock_con = threading.Condition()
        threads = []
        for i in range(5):
            threads.append(Producer())
        threads.append(Consumer())
        for t in threads:
            t.start()
        for t in threads:
            t.join()
    View Code

    queue:

    # _author: lily
    # _date: 2019/1/30
    
    import queue
    
    # q = queue.Queue()
    
    q = queue.Queue(3)  # 设置队列大小
    q.put('xiaoming', 0)
    q.put('xiaohong')
    q.put('xiaofang', 0)   # 队列大小为 2 ,当要放置第三个数据的时候,1会被阻塞,0会报错。默认参数为1
    
    print(q.get())
    print(q.get())
    print(q.get())
    print(q.get(0))   # 参数为 0 的时候如果队列空了,还去取值,就会报错。参数为 1 会被阻塞
    View Code
    猪猪侠要努力呀!
  • 相关阅读:
    A
    B
    C
    I
    公共最大字串长度
    docker run 的背后的故事(zz)
    python之多并发socket(zz)
    Python垃圾回收机制:gc模块(zz)
    我要做的git的分享(zz)
    SpringMVC框架入门配置 IDEA下搭建Maven项目(zz)
  • 原文地址:https://www.cnblogs.com/mlllily/p/10336553.html
Copyright © 2020-2023  润新知