zoukankan      html  css  js  c++  java
  • Python 线程间通信练习

    from threading import Lock,RLock
    import threading
    
    import time
    
    total = 0
    lock = RLock()
    
    
    def add():
        global total
        global lock
        for i in range(1000000):
            lock.acquire()
            lock.acquire()
            total+=1
            lock.release()
            lock.release()
    
    def desc():
        global total
        global lock
        for i in range(1000000):
            lock.acquire()
            total -= 1
            lock.release()
    
    start = time.time()
    add_threading = threading.Thread(target=add)
    desc_threading = threading.Thread(target=desc)
    add_threading.start()
    
    desc_threading.start()
    end = time.time()
    add_threading.join()
    
    desc_threading.join()
    print(total)
    print(end-start)
    
    # Semaphore 是用于控制进入数量的锁
    import threading
    
    import time
    
    
    class HtmlSpider(threading.Thread):
        def __init__(self, url, sem):
            super().__init__()
            self.url = url
            self.sem = sem
    
        def run(self):
            time.sleep(2)
            print('got html text success')
            self.sem.release()
    
    
    class UrlProducer(threading.Thread):
        def __init__(self, sem):
            super().__init__()
            self.sem = sem
    
        def run(self):
            for i in range(20):
                self.sem.acquire()
                html_thread = HtmlSpider('https://baidu.com/{}'.format(i), sem)
                html_thread.start()
    
    
    if __name__ == '__main__':
        # 一次允许3个并发
        sem = threading.Semaphore(3)
        url_producer = UrlProducer(sem)
        url_producer.start()
    
    
  • 相关阅读:
    常用Dos 命令
    Expect: 100continue
    Sql Server 文件和文件组体系结构
    Build Action
    regasm.exe 程序集注册工具
    获得user account的SID,GUID
    sp_change_users_login
    Regsvr32
    ASP.NET IIS 注册工具 (Aspnet_regiis.exe)
    随机生成300道四则运算
  • 原文地址:https://www.cnblogs.com/jeff-ideas/p/10540368.html
Copyright © 2011-2022 走看看