zoukankan      html  css  js  c++  java
  • python多线程知识-实用实例

    python多线程使用场景:IO操作,不适合CPU密集操作型任务
     
    1、多个线程内存共享
    2、线程同时修改同一份数据需要加锁,mutex互斥锁
    3、递归锁:多把锁,锁中有锁
    4、python多线程,同一时间只有颗CPU在执行。
     
    启动线程:
     1 import threading
     2 def run(name)
     3     print("run thread....")
     4 
     5 #创建进程对象,target=方法名,args=(参数1,参数b,)
     6 t = threading.Thread(target=run,args=(n,))
     7 #设置守护线程
     8 t.setDaemon(True)
     9 #启动线程
    10 t.start()
    11 #等待线程结束
    12 t.jion()

    型号量使用(线程池)

     1 import threading
     2 import time
     3 
     4 def run(n):
     5     #加锁
     6     semaphore.acquire()
     7     print("Look:%s"%n)
     8     time.sleep(0.5)
     9     #释放锁
    10     semaphore.release()
    11 
    12 if __name__ == "__main__":
    13     #同时准许5个线程
    14     semaphore = threading.BoundedSemaphore(5)
    15     tlist = []
    16     #设置多少个线程
    17     for i in range(33):
    18         t = threading.Thread(target=run,args=(i,))
    19         t.start()
    20         tlist.append(t)
    21     for r in tlist:
    22         r.jion()
  • 相关阅读:
    初识面向对象
    Git 子模块
    至今为止项目中遇到的问题
    vuex , 简单入(liao)门(jie)
    Git rebase
    Git
    js设计模式工厂模式
    vue slot
    Jquery学习,一道笔试题:关于表格【最近记】
    闭包与this学习
  • 原文地址:https://www.cnblogs.com/shangmo/p/9001946.html
Copyright © 2011-2022 走看看