• python 线程与进程


    线程和进程简介


    • 应用程序和进程以及线程的关系?
    • 一个应用程序里可以有多个进程,一个进程里可以有多个线程 最原始的计算机是如何运行的?
    • CPU是什么?为什么要使用多个CPU?
    • 为什么要使用多线程?
    • 为什么要使用多进程?
    • java和C#中的多线程和python多线程的区别?
    • python多线程和傻缺的GIL python
    • 如何让程序真正的实现同时运行?
    • 线程和进程的选择:计算密集型和IO密集型程序。(IO操作不占用CPU)

      进程的开销通常比线程昂贵, 因为线程自动共享内存地址空间和文件描述符. 意味着, 创建进程比创建线程会花费更多

      在执行一些sleep/read/write/recv/send这些会导致阻塞的函数时,当前线程会主动放弃GIL,然后调用相应的系统API,完成后再重新申请GIL。因此,GIL也并不是导致Python的多线程完全没用,在一些IO等待的场合,Python多线程还是发挥了作用,当然如果多线程都是用于CPU密集的代码,那多线程的执行效率就明显会比单线程的低。

    多线程开发


    threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。python当前版本的多线程库没有实现优先级、线程组,线程也不能被停止、暂停、恢复、中断。

    threading模块提供的类:  
      Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local。

    threading 模块提供的常用方法: 
      threading.currentThread(): 返回当前的线程变量。 
      threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 
      threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

    threading 模块提供的常量:

      threading.TIMEOUT_MAX 设置threading全局超时时间。

    Thread是线程类,有两种使用方法,直接传入要运行的方法或从Thread继承并覆盖run():

     1 #coding:utf8
     2 
     3 import threading
     4 import time
     5 
     6 #方法一,将要执行的方法作为参数传给Thread的构造方法
     7 def action(arg):
     8     time.sleep(1)
     9     print 'the arg is:%s
    ' %arg
    10     time.sleep(1)
    11     
    12 for i in xrange(3):
    13     t = threading.Thread(target=action,args=(i,))
    14     t.start()
    15     
    16 print 'main_thread end!'
    将要执行的方法作为参数传给Thread的构造方法
     1 #coding:Utf8
     2 import threading
     3 import time
     4 
     5 
     6 #方法二:从Thread继承,并重写run()
     7 class MyThread(threading.Thread):
     8     def __init__(self,arg):
     9         super(MyThread, self).__init__()#注意:一定要显式的调用父类的初始化函数。
    10         self.arg=arg
    11     def run(self):#定义每个线程要运行的函数
    12         time.sleep(1)
    13         print 'the arg is:%s
    ' % self.arg
    14 
    15 for i in xrange(4):
    16     t =MyThread(i)
    17     t.start()
    18 
    19 print 'main thread end!'
    从Thread继承,并重写run()

    构造方法: 
    Thread(group=None, target=None, name=None, args=(), kwargs={}) 

      group: 线程组,目前还没有实现,库引用中提示必须是None; 
      target: 要执行的方法; 
      name: 线程名; 
      args/kwargs: 要传入方法的参数。

    实例方法: 
      isAlive(): 返回线程是否在运行。正在运行指启动后、终止前。 
      get/setName(name): 获取/设置线程名。 

      start():  线程准备就绪,等待CPU调度
      is/setDaemon(bool): 获取/设置是后台线程(默认前台线程(False))。(在start之前设置)

        如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,主线程和后台线程均停止
             如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止
      start(): 启动线程。 
      join([timeout]): 阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。

     1 #coding:utf8
     2 import threading
     3 import time
     4 
     5 def action(arg):
     6     time.sleep(1)
     7     print 'sub thread start!The thread name is: %s
    ' % threading.currentThread().getName()
     8     print 'The arg is:%s
    ' %arg
     9     time.sleep(1)
    10     
    11 for i in xrange(4):
    12     t = threading.Thread(target=action,args=(i,))
    13     t.start()
    14     
    15 print 'main_thread end!'
    getName()
    1 main_thread end!
    2 sub thread start!The thread name is: Thread-1
    3 The arg is:0
    4 sub thread start!The thread name is: Thread-2
    5 The arg is:1
    6 sub thread start!The thread name is: Thread-3
    7 The arg is:2
    8 sub thread start!The thread name is: Thread-4
    9 The arg is:3
    运行结果
    可以看出,创建的4个“前台”线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止。
    验证了setDeamon(False)(默认)前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,主线程停止。
     1 #coding:UTF8
     2 
     3 import threading
     4 import  time
     5 
     6 def action(arg):
     7     time.sleep(1)
     8     print 'Sub thread start,The thread name is: %s
    ' % threading.currentThread().getName()
     9     print 'The arg is:' % arg
    10     time.sleep(1)
    11     
    12 for i in xrange(3):
    13     t = threading.Thread(target=action,args=(i,))
    14     t.setDaemon(True)
    15     t.start()
    16     
    17 print 'main_thread end!'
    setDaemon
    1 main_thread end!
    运行结果

    验证了setDeamon(True)后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,主线程均停止。

    设置join

     1 #coding:UTF8
     2 
     3 import threading
     4 import  time
     5 
     6 def action(arg):
     7     time.sleep(1)
     8     print 'Sub thread start,The thread name is: %s
    ' % threading.currentThread().getName()
     9     print 'The arg is: %s
    ' % arg
    10     time.sleep(1)
    11 
    12 thread_list = []    
    13 for i in xrange(3):
    14     t = threading.Thread(target=action,args=(i,))
    15     t.setDaemon(True)
    16     thread_list.append(t)
    17     
    18 for t in thread_list:
    19     t.start()
    20     
    21 for t in thread_list:
    22     t.join()
    23 print 'main_thread end!'
    join
    1 Sub thread start,The thread name is: Thread-2
    2 The arg is: 1
    3 Sub thread start,The thread name is: Thread-3
    4 The arg is: 2
    5 Sub thread start,The thread name is: Thread-1
    6 The arg is: 0
    7 main_thread end!
    运行结果
    设置join之后,主线程等待子线程全部执行完成后或者子线程超时后,主线程才结束

    验证了 join()阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout,即使设置了setDeamon(True)主线程依然要等待子线程结束。

    join不妥当的用法,使多线程编程顺序执行
     1 #coding:UTF8
     2 
     3 import threading
     4 import  time
     5 
     6 def action(arg):
     7     time.sleep(1)
     8     print 'Sub thread start,The thread name is: %s
    ' % threading.currentThread().getName()
     9     print 'The arg is: %s
    ' % arg
    10     time.sleep(1)
    11 
    12    
    13 for i in xrange(3):
    14     t = threading.Thread(target=action,args=(i,))
    15     t.setDaemon(True)
    16     t.start()
    17     t.join()
    18 print 'main_thread end!'
    join
    
    
     1 Sub thread start,The thread name is: Thread-1
     2 The arg is: 0
     3 Sub thread start,The thread name is: Thread-2
     4 The arg is: 1
     5 Sub thread start,The thread name is: Thread-3
     6 The arg is: 2
     7 main_thread end!
     8 
     9 
    10 可以看出此时,程序只能顺序执行,每个线程都被上一个线程的join阻塞,使得“多线程”失去了多线程意义。
    运行结果

    例子:(生产者与消费者模型)

     1 #coding:UTF8
     2 
     3 import threading
     4 from Queue import Queue
     5 import time
     6 
     7 class Producer(threading.Thread):
     8     
     9     def __init__(self,name,queue):
    10         '''
    11         @param name:生产者的名称
    12         @param queue:容器
    13         '''
    14         self.__Name = name
    15         self.__Queue = queue
    16         super(Producer,self).__init__()
    17         
    18     def run(self):
    19         while True:
    20             if self.__Queue.full():
    21                 time.sleep(1)
    22             else: 
    23                 self.__Queue.put('baozi')
    24                 time.sleep(1)
    25                 print '%s 生产了一个包子' %(self.__Name)
    26         #threading.Thread.run(self)
    27         
    28 
    29 class Consumer(threading.Thread):
    30     
    31     def __init__(self,name,queue):
    32         '''
    33         @param name:生产者的名称
    34         @param queue:容器
    35         '''
    36         self.__Name = name
    37         self.__Queue = queue
    38         super(Consumer,self).__init__()
    39         
    40     def run(self):
    41         while True:
    42             if self.__Queue.empty():
    43                 time.sleep(1)
    44             else:
    45                 self.__Queue.get()
    46                 time.sleep(1)
    47                 print '%s 消耗了一个包子' %(self.__Name)
    48 
    49         #threading.Thread.run(self)
    50 
    51 que = Queue(maxsize=100)
    52 
    53 baogou1 = Producer('老苟1',que)
    54 baogou1.start()
    55 baogou2 = Producer('老苟2',que)
    56 baogou2.start()
    57 baogou3 = Producer('老苟3',que)
    58 baogou3.start()
    59 
    60 for i in range(20):
    61     name = '奥黑子%d' %(i,)
    62     temp = Consumer(name,que)
    63     temp.start()
    64     
    65 
    66   
    67            
    View Code
     1 老苟1 生产了一个包子
     2 老苟2 生产了一个包子
     3 老苟3 生产了一个包子
     4 奥黑子0 消耗了一个包子
     5 奥黑子1 消耗了一个包子
     6 奥黑子2 消耗了一个包子
     7 .....
     8 
     9 
    10 一直循环下去
    运行结果

    Lock、Rlock类


      由于线程之间随机调度:某线程可能在执行n条后,CPU接着执行其他线程。为了多个线程同时操作一个内存中的资源时不产生混乱,我们使用锁。

    Lock(指令锁)是可用的最低级的同步指令。Lock处于锁定状态时,不被特定的线程拥有。Lock包含两种状态——锁定和非锁定,以及两个基本的方法。

    可以认为Lock有一个锁定池,当线程请求锁定时,将线程至于池中,直到获得锁定后出池。池中的线程处于状态图中的同步阻塞状态。

    RLock(可重入锁)是一个可以被同一个线程请求多次的同步指令。RLock使用了“拥有的线程”和“递归等级”的概念,处于锁定状态时,RLock被某个线程拥有。拥有RLock的线程可以再次调用acquire(),释放锁时需要调用release()相同次数。

    可以认为RLock包含一个锁定池和一个初始值为0的计数器,每次成功调用 acquire()/release(),计数器将+1/-1,为0时锁处于未锁定状态。

    简言之:Lock属于全局,Rlock属于线程。

    构造方法: 
    Lock(),Rlock(),推荐使用Rlock()

    实例方法: 
      acquire([timeout]): 尝试获得锁定。使线程进入同步阻塞状态。 
      release(): 释放锁。使用前线程必须已获得锁定,否则将抛出异常。

     1 #coding:UTF8
     2 
     3 import threading
     4 import time
     5 
     6 gl_num = 0
     7 
     8 def show(arg):
     9     global gl_num
    10     time.sleep(1)
    11     gl_num += 1
    12     print  gl_num
    13     
    14 for i in range(10):
    15     t = threading.Thread(target=show,args=(i,))
    16     t.start()
    17     
    18 print 'main_thread stop!'
    未使用锁
     1 main_thread stop!
     2 1
     3 2
     4 34
     5  
     6  56
     7 
     8 7
     9 91010
    10 
    11 
    12 多次运行可能产生混乱。这种场景就是适合使用锁的场景。
    运行结果
     1 #coding:UTF8
     2 
     3 import threading
     4 import time
     5 
     6 gl_num = 0
     7 
     8 Lock = threading.RLock()
     9 
    10 
    11 # 调用acquire([timeout])时,线程将一直阻塞,
    12 # 直到获得锁定或者直到timeout秒后(timeout参数可选)。
    13 # 返回是否获得锁
    14 def show(arg):
    15     Lock.acquire()
    16     global gl_num
    17     time.sleep(1)
    18     gl_num += 1
    19     print  gl_num
    20     Lock.release()
    21     
    22 for i in range(10):
    23     t = threading.Thread(target=show,args=(i,))
    24     t.start()
    25     
    26 print 'main_thread stop!'
    使用锁
     1 main_thread stop!
     2 1
     3 2
     4 3
     5 4
     6 5
     7 6
     8 7
     9 8
    10 9
    11 10
    12 
    13 
    14 可以看出,全局变量在在每次被调用时都要获得锁,才能操作,因此保证了共享数据的安全性
    运行结果

     Lock对比Rlock

     1 #coding:UTF8
     2 
     3 import threading
     4 
     5 lock = threading.Lock()
     6 lock.acquire()
     7 lock.acquire() #产生了死锁
     8 
     9 lock.release()
    10 lock.release()
    11 
    12 print lock.acquire()

    没有结果输出

    1 #coding:utf8
    2 import threading
    3 rLock = threading.RLock()  #RLock对象
    4 rLock.acquire()
    5 rLock.acquire() ##在同一线程内,程序不会堵塞。
    6 rLock.release()
    7 rLock.release()
    8 print rLock.acquire

     输出结果:

      <bound method _RLock.acquire of <_RLock owner=None count=0>>


    Condition类


      Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。

      可以认为,除了Lock带有的锁定池外,Condition还包含一个等待池,池中的线程处于等待阻塞状态,直到另一个线程调用notify()/notifyAll()通知;得到通知后线程进入锁定池等待锁定。

    构造方法: 
    Condition([lock/rlock])

    实例方法: 
      acquire([timeout])/release(): 调用关联的锁的相应方法。 
      wait([timeout]): 调用这个方法将使线程进入Condition的等待池等待通知,并释放锁。使用前线程必须已获得锁定,否则将抛出异常。 
      notify(): 调用这个方法将从等待池挑选一个线程并通知,收到通知的线程将自动调用acquire()尝试获得锁定(进入锁定池);其他线程仍然在等待池中。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。 
      notifyAll(): 调用这个方法将通知等待池中所有的线程,这些线程都将进入锁定池尝试获得锁定。调用这个方法不会释放锁定。使用前线程必须已获得锁定,否则将抛出异常。

    例子:

     1 #coding:UTF8
     2 
     3 import threading
     4 import time
     5 
     6 # 商品
     7 product = None
     8 # 条件变量
     9 con = threading.Condition()
    10 
    11 
    12 # 生产者方法
    13 def produce():
    14     global product
    15 
    16     if con.acquire():
    17         while True:
    18             if product is None:
    19                 print 'produce...'
    20                 product = 'anything'
    21 
    22                 # 通知消费者,商品已经生产
    23                 con.notify()
    24 
    25             # 等待通知
    26             con.wait()
    27             time.sleep(2)
    28 
    29 
    30 # 消费者方法
    31 def consume():
    32     global product
    33 
    34     if con.acquire():
    35         while True:
    36             if product is not None:
    37                 print 'consume...'
    38                 product = None
    39 
    40                 # 通知生产者,商品已经没了
    41                 con.notify()
    42 
    43             # 等待通知
    44             con.wait()
    45             time.sleep(2)
    46 
    47 
    48 t1 = threading.Thread(target=produce)
    49 t2 = threading.Thread(target=consume)
    50 t2.start()
    51 t1.start()
    生产者消费者模型
     1 produce...
     2 consume...
     3 produce...
     4 consume...
     5 produce...
     6 consume...
     7 produce...
     8 consume...
     9 produce...
    10 consume...
    11 produce...
    12 
    13 
    14 一直循环下去
    运行结果

    例二:

     1 #coding:UTF8
     2 
     3 import threading
     4 import time
     5 
     6 condition = threading.Condition()
     7 products = 0
     8 
     9 class Producer(threading.Thread):
    10     def run(self):
    11         global products
    12         while True:
    13             if condition.acquire():
    14                 if products < 10:
    15                     products += 1;
    16                     print "Producer(%s):deliver one, now products:%s" %(self.name, products)
    17                     condition.notify()#不释放锁定,因此需要下面一句
    18                     condition.release()
    19                 else:
    20                     print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products)
    21                     condition.wait();#自动释放锁定
    22                 time.sleep(2)
    23 
    24 class Consumer(threading.Thread):
    25     def run(self):
    26         global products
    27         while True:
    28             if condition.acquire():
    29                 if products > 1:
    30                     products -= 1
    31                     print "Consumer(%s):consume one, now products:%s" %(self.name, products)
    32                     condition.notify()
    33                     condition.release()
    34                 else:
    35                     print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products)
    36                     condition.wait();
    37                 time.sleep(2)
    38 
    39 if __name__ == "__main__":
    40     for p in range(0, 2):
    41         p = Producer()
    42         p.start()
    43 
    44     for c in range(0, 3):
    45         c = Consumer()
    46         c.start()
    生产者消费者模型
     1 Producer(Thread-1):deliver one, now products:1
     2 Producer(Thread-2):deliver one, now products:2
     3 Consumer(Thread-3):consume one, now products:1
     4 Consumer(Thread-4):only 1, stop consume, products:1
     5 Consumer(Thread-5):only 1, stop consume, products:1
     6 Producer(Thread-2):deliver one, now products:2
     7 Consumer(Thread-4):consume one, now products:1
     8 Consumer(Thread-4):only 1, stop consume, products:1
     9 Producer(Thread-1):deliver one, now products:2
    10 Consumer(Thread-3):consume one, now products:1
    11 Producer(Thread-2):deliver one, now products:2
    12 Consumer(Thread-5):consume one, now products:1
    13 
    14 
    15 
    16 循环下去
    运行结果

    例三:

     1 #coding:UTF8
     2 import threading
     3  
     4 alist = None
     5 condition = threading.Condition()
     6  
     7 def doSet():
     8     if condition.acquire():
     9         while alist is None:
    10             condition.wait()
    11         for i in range(len(alist))[::-1]:
    12             alist[i] = 1
    13         condition.release()
    14  
    15 def doPrint():
    16     if condition.acquire():
    17         while alist is None:
    18             condition.wait()
    19         for i in alist:
    20             print i,
    21         print
    22         condition.release()
    23  
    24 def doCreate():
    25     global alist
    26     if condition.acquire():
    27         if alist is None:
    28             alist = [0 for i in range(10)]
    29             condition.notifyAll()
    30         condition.release()
    31  
    32 tset = threading.Thread(target=doSet,name='tset')
    33 tprint = threading.Thread(target=doPrint,name='tprint')
    34 tcreate = threading.Thread(target=doCreate,name='tcreate')
    35 tset.start()
    36 tprint.start()
    37 tcreate.start()
    生产者消费者模型
    1 0 0 0 0 0 0 0 0 0 0
    运行结果

    Event类


      Event(事件)是最简单的线程通信机制之一:一个线程通知事件,其他线程等待事件。Event内置了一个初始为False的标志,当调用set()时设为True,调用clear()时重置为 False。wait()将阻塞线程至等待阻塞状态。

      Event其实就是一个简化版的 Condition。Event没有锁,无法使线程进入同步阻塞状态。

    构造方法: 
    Event()

    实例方法: 
      isSet(): 当内置标志为True时返回True。 
      set(): 将标志设为True,并通知所有处于等待阻塞状态的线程恢复运行状态。 
      clear(): 将标志设为False。 
      wait([timeout]): 如果标志为True将立即返回,否则阻塞线程至等待阻塞状态,等待其他线程调用set()。

     

    例子一

     1 #coding:UTF8
     2 
     3 import threading
     4 import time
     5 
     6 event = threading.Event()
     7 
     8 
     9 def func():
    10     # 等待事件,进入等待阻塞状态
    11     print '%s wait for event...' % threading.currentThread().getName()
    12     event.wait()
    13 
    14     # 收到事件后进入运行状态
    15     print '%s recv event.' % threading.currentThread().getName()
    16 
    17 
    18 t1 = threading.Thread(target=func)
    19 t2 = threading.Thread(target=func)
    20 t1.start()
    21 t2.start()
    22 
    23 time.sleep(2)
    24 
    25 # 发送事件通知
    26 print 'MainThread set event.'
    27 event.set()
    View Code
    1 Thread-1 wait for event...
    2 Thread-2 wait for event...
    3 MainThread set event.
    4 Thread-1 recv event.
    5 Thread-2 recv event.
    运行结果

    timer类


      Timer(定时器)是Thread的派生类,用于在指定时间后调用一个方法。

    构造方法: 
    Timer(interval, function, args=[], kwargs={}) 
      interval: 指定的时间 
      function: 要执行的方法 
      args/kwargs: 方法的参数

    实例方法: 
    Timer从Thread派生,没有增加实例方法。

     例:

     1 #coding:UTF8
     2 import threading
     3 
     4 
     5 def func():
     6     print 'hello timer!'
     7 
     8 
     9 timer = threading.Timer(5, func)
    10 timer.start()
    View Code

    线程延迟5秒后执行。


    local类


       local是一个小写字母开头的类,用于管理 thread-local(线程局部的)数据。对于同一个local,线程无法访问其他线程设置的属性;线程设置的属性不会被其他线程设置的同名属性替换。

      可以把local看成是一个“线程-属性字典”的字典,local封装了从自身使用线程作为 key检索对应的属性字典、再使用属性名作为key检索属性值的细节。

     1 #coding:UTF8
     2 import threading
     3  
     4 local = threading.local()
     5 local.tname = 'main'
     6  
     7 def func():
     8     local.tname = 'notmain'
     9     print local.tname
    10  
    11 t1 = threading.Thread(target=func)
    12 t1.start()
    13 t1.join()
    14  
    15 print local.tname
    View Code
    1 notmain
    2 main
    运行结果
  • 相关阅读:
    jQuery 取选中的radio的值方法
    点击不同的span,追加当前class属性,并移除其他span
    Visual Studio快捷键
    hadoop官网介绍及如何下载hadoop(2.4)各个版本与查看hadoop API介绍
    TCP的状态
    圣思园java se培训总结(82-)(观察者设计模式)
    圣思园java se培训总结(78-)(swing的设计模式,观察者设计模式)
    圣思园java se培训总结(69-)(Annotation,异常处理)
    圣思园java se培训总结(58-)(java1.5新特性,可变参数,包装类)
    圣思园java se培训总结(52-)(泛型)
  • 原文地址:https://www.cnblogs.com/qianyuliang/p/6414678.html
Copyright © 2020-2023  润新知