多线程---threading

时间:2020-03-27
本文章向大家介绍多线程---threading,主要包括多线程---threading使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,几个概念:

  • GIL:  Global Interpreter Lock,全局解释器锁。为了解决多线程之间数据完整性和状态同步的问题,设计为在任意时刻只有一个线程在解释器中运行。
  • 线程:程序执行的最小单位。
  • 进程:系统资源分配的最小单位。
  • 线程安全:多线程环境中,共享数据同一时间只能有一个线程来操作。
  • 原子操作:原子操作就是不会因为进程并发或者线程并发而导致被中断的操作。

2,threading:

  thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 "_thread"。

threading.thread原型:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
   # group should be None; reserved for future extension when a ThreadGroup class is implemented
    #target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called
    #name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number
    #args is the argument tuple for the target invocation. Defaults to ().
    #kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
    #If not None, daemon explicitly sets whether the thread is daemonic. If None (the default), the daemonic property is inherited from the current thread

thread method:

start()
    #用于启动thread的run方法,每个thread最多只需调用一次start(),如果多次调用,会引起RuntimeError错误
run()
    #从target和kwargs获取相应的参数,run当前thread,可以通过is_alive查看thread状态是否为alive
join(timeout=None)
    #join用于等待thread结束;join使线程具有阻塞属性,只有当前thread的join结束之后,下一个线程才可以开启
   # 默认timeout=None时,线程可能正常或者异常终止;当timeout不为None时,join超时后也会退出
    #需要先start再join,否则会报错
is_alive()
    #返回当前thread的状态,用于判断是否alive

class threading.Lock

acquire(blocking=True, timeout=-1)
    #用于获取lock锁,默认时阻塞的,timeout=-1表示等待时间无限制;否则按timeout指定值按秒计数等待
release()
    #release a lock,释放锁

example1:

原文地址:https://www.cnblogs.com/zhiminyu/p/12584185.html