zoukankan      html  css  js  c++  java
  • python线程间通信

    
    
    #!/usr/bin/python
    # -*- coding:utf8 -*-
    
    from threading import Thread, Lock
    import random
    
    
    def test_thread():
        # 线程间的通信
        # 使用锁来控制共享资源的访问
        a = 0
        n = 10000000
        lock = Lock()
    
        def imcr(n):
            global a
            for i in range(n):
                lock.acquire()  # 可以写成with lock:
                a += 1  # a+=1
                lock.release()
    
        def decr(n):
            for i in range(n):
                global a
                lock.acquire()
                a -= 1
                lock.release()
    
        t = Thread(target=imcr, args=(n,))
        t2 = Thread(target=decr, args=(n,))
        t.start()
    
        t2.start()
        t.join()
        t2.join()
        print(a)
    
    
    # 多线程的消费者与生产者模式
    # from threading import Thread
    from queue import Queue
    
    q = Queue(3)
    
    
    class Producter(Thread):
        def __init__(self, queue):
            super().__init__()
            self.queue = queue
    
        def run(self):
            while True:
                item = random.randint(0, 99)
                self.queue.put(item)
                print('已产生%s' % item)
    
    
    class Consumer(Thread):
        def __init__(self, queue):
            super().__init__()
            self.queue = queue
    
        def run(self):
            while True:
                item = self.queue.get()
                print(item)
                self.queue.task_done()  # 告诉队列这个任务执行完成
    
    
    product = Producter(q)
    consumer = Consumer(q)
    product.start()
    consumer.start()
    
    # 注意,mgr=Manger() q.mgr.Queue()
    # 进程版本的需要加一个input()或者是
    # producter.join consumer.join()  因为一旦主进程结束,代码就不会继续运行了
    
    
    
  • 相关阅读:
    docker常用命令
    Jenkins 插件开发记录
    【转】python作用域
    git备忘录
    【笔记】script.sh: source: not found in docker 问题
    (转)JavaScript判断浏览器类型及版本
    (转)webstorm快捷键
    (转)javaScript call 函数的用法说明
    (转载)记录函数 getStyle() 获取元素 CSS 样式
    (转)resize扩展
  • 原文地址:https://www.cnblogs.com/lajiao/p/11685771.html
Copyright © 2011-2022 走看看