xi123的个人博客分享 http://blog.sciencenet.cn/u/xi123

博文

python多线程编程

已有 1498 次阅读 2017-12-14 10:44 |个人分类:python学习|系统分类:科研笔记

       Python是支持多线程的,主要通过thread和threading两个模块来实现,其中thread模块比较底层(或者说是轻量级的),而threading模块对thread做了一些包装,可以更加方便地被使用。  

Note1:The thread module has been renamed to _thread in Python 3.The 2to3 tool will automatically adapt imports when converting yoursources to Python 3; however, you should consider using the high-levelthreading module instead.

Note2:Starting with Python 2.6,  threading module provides PEP 8 compliant aliases andproperties to replace the camelCase names that were inspired by Java’sthreading API. This updated API is compatible with that of themultiprocessing module. However, no schedule has been set for thedeprecation of the camelCase names and they remain fully supported inboth Python 2.x and 3.x.


1、thread模块

   thread.LockType :锁对象的一种,用于线程同步

   thread.error:线程异常

  thread.start_new_thread(function, args[, kwargs]):创建一个新的线程

            function:线程执行函数

            args:线程执行函数的参数,是一个元组类型数据

            kwargs:字典(可为空)

            return:线程的表示符

    thread.exit() :线程退出函数

 thread.allocate_lock() :生成一个未锁状态的锁对象返回值

2、threading模块

     经常和Queue结合使用,Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列QueueLIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。

     常用函数:

  • threading.active_count()  :返回当前线程对象Thread的个数(Return the number of Thread objects currently alive.  The returned count is equal to the length of the list returned by enumerate().)

  • threading.enumerate()  :返回当前运行的线程对象Thread(包括后台的)的list

  • threading.Condition()  :返回条件变量对象的工厂函数,主要用户线程的并发(A factory

    function that returns a new condition variable object. A conditionvariable
    allows one or more threads to wait until they are notified by another thread.)

  • threading.current_thread()  :返回当前的线程对象Thread(Return the current Thread
    object, corresponding to the caller’s thread of control.  If the caller’s
    thread of control was not created through the threading module, a dummy thread
    object with limited functionality is returned.)

  • threading.Lock()  :返回一个新的锁对象,是在thread模块的基础上实现的,与acquire()和release()
    结合使用(A factory function that returns a new primitive lock object.
    Once a thread hasacquired it, subsequent attempts to acquire it block, until
    it is released; anythread may release it.)

 常用类:

  • threading.Thread  :一个表示线程控制的类, 这个类常被继承(A class that represents a
    thread of control.  This class can be safelysubclassed in a limited fashion.)

  • thraeding.Timer  :定时器,线程在一定时间后执行(A thread that executes a function
    after a specified interval has passed.)

  • threading.ThreadError  :引发中各种线程相关异常(Raised for various threading-related
    errors as described below.  Note thatmany interfaces use RuntimeError instead
    of ThreadError.)

      Thread对象This class represents an activity that is run in a separate thread of control. There are two ways to specify the activity:  

       by passing a callable object to the constructor                                                                

       by overriding the run() method in a subclass.

   No other methods (except for the constructor) should be overridden in a subclass.  In other words,  only  override the __init__() and run() methods of this class.

   Once a thread object is created, its activity must be started by calling the thread’s start() method.  This invokes the run() method in aseparate thread of control.

   Once the thread’s activity is started, the thread is considered ‘alive’. Itstops being alive when its run() method terminates – either normally, orby raising an unhandled exception.  The is_alive() method tests whether thethread is alive.




threading.Thread(group = None, target = None, name = None, args = () kwars = {})

       group : 应该为None(reserved for future extension when aThreadGroup class is implemented.)

  target : 可以传入一个函数用于run()方法调用

  name : 线程名 默认使用"Thread-N"

  args : 元组, 表示传入target函数的参数

  kwargs : 字典, 传入target函数中关键字参数

作者:Andrew_liu
链接:http://www.jianshu.com/p/86b8e78c418a
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 属性:

   name  #线程表示, 没有任何语义

   doemon  #布尔值, 如果是守护线程为True, 不是为False, 主线程不是守护线程, 默认threading.Thread.damon = False

   类方法:



   run()  #用以表示线程活动的方法。

   start()  #启动线程活动。  

   join([time])  #等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出

或者抛出未处理的异常-或者是可选的超时发生。

   isAlive(): 返回线程是否活动的。

   getName(): 返回线程名。

   setName(): 设置线程名。



参考资料:

【1】http://www.jianshu.com/p/86b8e78c418a?search_token=4d8e9a843325f3abd4be64fb668ec7812f760bc1f9aa7b10431fa8966453a868

【2】https://docs.python.org/2/library/threading.html

【3】https://docs.python.org/2/library/thread.html#module-thread

【4】http://blog.csdn.net/u013787595/article/details/49446291

【5】https://www.ibm.com/developerworks/aix/library/au-threadingpython/(先学)

【6】http://python.jobbole.com/85050/

【7】https://www.cnblogs.com/fnng/p/3670789.html

【8】https://github.com/moranzcw/Zhihu-Spider/tree/master/spider

 

     



















           




https://blog.sciencenet.cn/blog-3360373-1089604.html

上一篇:Win7下Gephi9.2的安装
下一篇:window7下anaconda安装
收藏 IP: 124.16.148.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-22 00:35

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部