zoukankan      html  css  js  c++  java
  • 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)



     
  • 相关阅读:
    笔记本越用越慢的解决方法。
    ubuntu 16.04 的IP地址变更
    如何把路由器当作交换机来使用
    通过 rufus 创建启动U盘,安装 VMWare Esxi
    Enable SMB2 on the Client
    Shiro入门学习与实战(一)
    Linux下Nginx1.9.9的安装
    Activiti工作流学习之SpringBoot整合Activiti5.22.0实现在线设计器(二)
    Activiti工作流学习之概述(一)
    Sqoop的安装及常用命令
  • 原文地址:https://www.cnblogs.com/shamoguzhou/p/15007427.html
Copyright © 2011-2022 走看看