• 7/13/2021python 核心编程020215


    生产者与消费者的解耦问题:

    耦合时代码之前联系性很强,不好

    解耦: 减少之间的联系

    所以第一版本就要想的长远一点 

    这个例子使用队列作为缓冲部分

    #encoding=utf-8
    import threading
    import time
    from queue import Queue

    class Producer(threading.Thread):
    def run(self):
    global queue
    count = 0
    while True:
    if queue.qsize()<1000:
    count = count +1
    msg = '生产产品'+str(count)
    queue.put(msg)
    print(msg)
    time.sleep(1)

    class Consumer(threading.Thread):
    def run(self):
    global queue
    count = 0
    while True:
    if queue.qsize()>100:
    for i in range(3):
    msg = self.name +'消费了'+queue.get()
    print(msg)
    time.sleep(1)

    if __name__ == "__main__":
    queue = Queue()
    for i in range(500):
    queue.put("初始产品"+str(i))
    for i in range(2):
    p = Producer()
    p.start()
    for i in range(5):
    c = Consumer()
    c.start()
    ThreadLocal在线程中的应用
    这是一个特殊的全局变量,多线程访问可以独自使用不会对其它线程有影响
    一般来说,全局变量是共享的对于多线程
    import threading

    #创建全局threadlocal对象
    local_school = threading.local()

    def process_student():
    #获取当前线程关联的student:
    std = local_school.student
    print("hello, %s (in %s)"%(std, threading.current_thread().name))

    def process_thread(name):
    #绑定threadlocal的student
    local_school.student = name #注意。可以增添一个属性
    process_student()

    t1 = threading.Thread(target= process_thread, args=('dongge',), name='Thread-A')
    t2 = threading.Thread(target= process_thread, args=('laowang',), name='Thread-B')
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    Result:

    hello, dongge (in Thread-A)
    hello, laowang (in Thread-B)



     
  • 相关阅读:
    「CF505E」 Mr. Kitayuta vs. Bamboos
    「CF1438D」 Powerful Ksenia
    Kruskal重构树
    20210528模拟赛总结
    20210527模拟赛总结
    20210526模拟赛总结
    20210525模拟赛总结
    CF #722 Div2题解
    洛谷P3652 csh和zzy的战争 题解
    [清华集训2012]模积和 题解
  • 原文地址:https://www.cnblogs.com/shamoguzhou/p/15007427.html
Copyright © 2020-2023  润新知