• python之线程


    一、线程与进程

    进程有很多优点,它提供了多道编程,让我们感觉我们每个人都拥有自己的CPU和其他资源,可以提高计算机的利用率。很多人就不理解了,既然进程这么优秀,为什么还要线程呢?其实,仔细观察就会发现进程还是有很多缺陷的,主要体现在两点上:

    • 进程只能在一个时间干一件事,如果想同时干两件事或多件事,进程就无能为力了。

    • 进程在执行的过程中如果阻塞,例如等待输入,整个进程就会挂起,即使进程中有些工作不依赖于输入的数据,也将无法执行。

      如果这两个缺点理解比较困难的话,举个现实的例子也许你就清楚了:如果把我们上课的过程看成一个进程的话,那么我们要做的是耳朵听老师讲课,手上还要记笔记,脑子还要思考问题,这样才能高效的完成听课的任务。而如果只提供进程这个机制的话,上面这三件事将不能同时执行,同一时间只能做一件事,听的时候就不能记笔记,也不能用脑子思考,这是其一;如果老师在黑板上写演算过程,我们开始记笔记,而老师突然有一步推不下去了,阻塞住了,他在那边思考着,而我们呢,也不能干其他事,即使你想趁此时思考一下刚才没听懂的一个问题都不行,这是其二。

      现在你应该明白了进程的缺陷了,而解决的办法很简单,我们完全可以让听、写、思三个独立的过程,并行起来,这样很明显可以提高听课的效率。而实际的操作系统中,也同样引入了这种类似的机制——线程。

    60年代,在OS中能拥有资源和独立运行的基本单位是进程,然而随着计算机技术的发展,进程出现了很多弊端,一是由于进程是资源拥有者,创建、撤消与切换存在较大的时空开销,因此需要引入轻型进程;二是由于对称多处理机(SMP)出现,可以满足多个运行单位,而多个进程并行开销过大。
      因此在80年代,出现了能独立运行的基本单位——线程(Threads)。
      注意:进程是资源分配的最小单位,线程是CPU调度的最小单位.
         每一个进程中至少有一个线程。 

    1.2 线程与进程 关系

    线程与进程的区别可以归纳为以下4点:
      1)地址空间和其它资源(如打开文件):进程间相互独立,同一进程的各线程间共享。某进程内的线程在其它进程不可见。
      2)通信:进程间通信IPC,线程间可以直接读写进程数据段(如全局变量)来进行通信——需要进程同步和互斥手段的辅助,以保证数据的一致性。
      3)调度和切换:线程上下文切换比进程上下文切换要快得多。
      4)在多线程操作系统中,进程不是一个可执行的实体。

    1.3 线程特点

    在多线程的操作系统中,通常是在一个进程中包括多个线程,每个线程都是作为利用CPU的基本单位,是花费最小开销的实体。线程具有以下属性。
      1)轻型实体
      线程中的实体基本上不拥有系统资源,只是有一点必不可少的、能保证独立运行的资源。
      线程的实体包括程序、数据和TCB。线程是动态概念,它的动态特性由线程控制块TCB(Thread Control Block)描述。
      2)独立调度和分派的基本单位。
      在多线程OS中,线程是能独立运行的基本单位,因而也是独立调度和分派的基本单位。由于线程很“轻”,故线程的切换非常迅速且开销小(在同一进程中的)。
      3)共享进程资源。
      线程在同一进程中的各个线程,都可以共享该进程所拥有的资源,这首先表现在:所有线程都具有相同的进程id,这意味着,线程可以访问该进程的每一个内存资源;此外,还可以访问进程所拥有的已打开文件、定时器、信号量机构等。由于同一个进程内的线程共享内存和文件,所以线程之间互相通信不必调用内核。
      4)可并发执行。
      在一个进程中的多个线程之间,可以并发执行,甚至允许在一个进程中所有线程都能并发执行;同样,不同进程中的线程也能并发执行,充分利用和发挥了处理机与外围设备并行工作的能力

    二、用户级线程与内核级线程

    1 1 内核支持线程是OS内核可感知的,而用户级线程是OS内核不可感知的。
    2 2 用户级线程的创建、撤消和调度不需要OS内核的支持,是在语言(如Java)这一级处理的;而内核支持线程的创建、撤消和调度都需OS内核提供支持,而且与进程的创建、撤消和调度大体是相同的。
    3 3 用户级线程执行系统调用指令时将导致其所属进程被中断,而内核支持线程执行系统调用指令时,只导致该线程被中断。
    4 4 在只有用户级线程的系统内,CPU调度还是以进程为单位,处于运行状态的进程中的多个线程,由用户程序控制线程的轮换运行;在有内核支持线程的系统内,CPU调度则以线程为单位,由OS的线程调度程序负责线程的调度。
    5 5 用户级线程的程序实体是运行在用户态下的程序,而内核支持线程的程序实体则是可以运行在任何状态下的程序。
    区别
    1 优点:当有多个处理机时,一个进程的多个线程可以同时执行。
    2 缺点:由内核进行调度。
    内核级优缺点
    1 优点:
    2 线程的调度不需要内核直接参与,控制简单。
    3 可以在不支持线程的操作系统中实现。
    4 创建和销毁线程、线程切换代价等线程管理的代价比内核线程少得多。
    5 允许每个进程定制自己的调度算法,线程管理比较灵活。
    6 线程能够利用的表空间和堆栈空间比内核级线程多。
    7 同一进程中只能同时有一个线程在运行,如果有一个线程使用了系统调用而阻塞,那么整个进程都会被挂起。另外,页面失效也会产生同样的问题。
    8 缺点:
    9 资源调度按照进程进行,多个处理机下,同一个进程中的线程只能在同一个处理机下分时复用
    用户级优缺点
    1 用户级与内核级的多路复用,内核同一调度内核线程,每个内核线程对应n个用户线程
    混合实现

    三、 线程与python

    3.1 全局解释器锁GIL

      Python代码的执行由Python虚拟机(也叫解释器主循环)来控制。Python在设计之初就考虑到要在主循环中,同时只有一个线程在执行。虽然 Python 解释器中可以“运行”多个线程,但在任意时刻只有一个线程在解释器中运行。
      对Python虚拟机的访问由全局解释器锁(GIL)来控制,正是这个锁能保证同一时刻只有一个线程在运行。

      在多线程环境中,Python 虚拟机按以下方式执行:

      a、设置 GIL;

      b、切换到一个线程去运行;

      c、运行指定数量的字节码指令或者线程主动让出控制(可以调用 time.sleep(0));

      d、把线程设置为睡眠状态;

      e、解锁 GIL;

      d、再次重复以上所有步骤。
      在调用外部代码(如 C/C++扩展函数)的时候,GIL将会被锁定,直到这个函数结束为止(由于在这期间没有Python的字节码被运行,所以不会做线程切换)编写扩展的程序员可以主动解锁GIL。

    3.2 python线程模块的选择

      Python提供了几个用于多线程编程的模块,包括thread、threading和Queue等。thread和threading模块允许程序员创建和管理线程。thread模块提供了基本的线程和锁的支持,threading提供了更高级别、功能更强的线程管理的功能。Queue模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构。
      避免使用thread模块,因为更高级别的threading模块更为先进,对线程的支持更为完善,而且使用thread模块里的属性有可能会与threading出现冲突;其次低级别的thread模块的同步原语很少(实际上只有一个),而threading模块则有很多;再者,thread模块中当主线程结束时,所有的线程都会被强制结束掉,没有警告也不会有正常的清除工作,至少threading模块能确保重要的子线程退出后进程才退出。

      thread模块不支持守护线程,当主线程退出时,所有的子线程不论它们是否还在工作,都会被强行退出。而threading模块支持守护线程,守护线程一般是一个等待客户请求的服务器,如果没有客户提出请求它就在那等着,如果设定一个线程为守护线程,就表示这个线程是不重要的,在进程退出的时候,不用等待这个线程退出。

    3.3 threading模块
    multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,因而不再详细介绍

     1 from threading import Thread
     2 import time
     3 def sayhi(name):
     4     time.sleep(2)
     5     print('%s say hello' %name)
     6 
     7 if __name__ == '__main__':
     8     t=Thread(target=sayhi,args=('egon',))
     9     t.start()
    10     print('主线程')
    11 
    12 
    13 
    14 from threading import Thread
    15 import time
    16 class Sayhi(Thread):
    17     def __init__(self,name):
    18         super().__init__()
    19         self.name=name
    20     def run(self):
    21         time.sleep(2)
    22         print('%s say hello' % self.name)
    23 
    24 
    25 if __name__ == '__main__':
    26     t = Sayhi('egon')
    27     t.start()
    28     print('主线程')
    创建

    多线程与多进程

     1 from threading import Thread
     2 from multiprocessing import Process
     3 import os
     4 
     5 def work():
     6     print('hello',os.getpid())
     7 
     8 if __name__ == '__main__':
     9     #part1:在主进程下开启多个线程,每个线程都跟主进程的pid一样
    10     t1=Thread(target=work)
    11     t2=Thread(target=work)
    12     t1.start()
    13     t2.start()
    14     print('主线程/主进程pid',os.getpid())
    15 
    16     #part2:开多个进程,每个进程都有不同的pid
    17     p1=Process(target=work)
    18     p2=Process(target=work)
    19     p1.start()
    20     p2.start()
    21     print('主线程/主进程pid',os.getpid())
    pid比较
     1 from threading import Thread
     2 from multiprocessing import Process
     3 import os
     4 
     5 def work():
     6     print('hello')
     7 
     8 if __name__ == '__main__':
     9     #在主进程下开启线程
    10     t=Thread(target=work)
    11     t.start()
    12     print('主线程/主进程')
    13     '''
    14     打印结果:
    15     hello
    16     主线程/主进程
    17     '''
    18 
    19     #在主进程下开启子进程
    20     t=Process(target=work)
    21     t.start()
    22     print('主线程/主进程')
    23     '''
    24     打印结果:
    25     主线程/主进程
    26     hello
    27     '''
    开启效率
     1 from  threading import Thread
     2 from multiprocessing import Process
     3 import os
     4 def work():
     5     global n
     6     n=0
     7 
     8 if __name__ == '__main__':
     9     # n=100
    10     # p=Process(target=work)
    11     # p.start()
    12     # p.join()
    13     # print('主',n) #毫无疑问子进程p已经将自己的全局的n改成了0,但改的仅仅是它自己的,查看父进程的n仍然为100
    14 
    15 
    16     n=1
    17     t=Thread(target=work)
    18     t.start()
    19     t.join()
    20     print('',n) #查看结果为0,因为同一进程内的线程之间共享进程内的数据
    内存数据共享

    多线程实现socket

     1 #_*_coding:utf-8_*_
     2 #!/usr/bin/env python
     3 import multiprocessing
     4 import threading
     5 
     6 import socket
     7 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
     8 s.bind(('127.0.0.1',8080))
     9 s.listen(5)
    10 
    11 def action(conn):
    12     while True:
    13         data=conn.recv(1024)
    14         print(data)
    15         conn.send(data.upper())
    16 
    17 if __name__ == '__main__':
    18 
    19     while True:
    20         conn,addr=s.accept()
    21 
    22 
    23         p=threading.Thread(target=action,args=(conn,))
    24         p.start()
    server
     1 #_*_coding:utf-8_*_
     2 #!/usr/bin/env python
     3 
     4 
     5 import socket
     6 
     7 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
     8 s.connect(('127.0.0.1',8080))
     9 
    10 while True:
    11     msg=input('>>: ').strip()
    12     if not msg:continue
    13 
    14     s.send(msg.encode('utf-8'))
    15     data=s.recv(1024)
    16     print(data)
    client

    Thread类的其他方法

     1 Thread实例对象的方法
     2   # isAlive(): 返回线程是否活动的。
     3   # getName(): 返回线程名。
     4   # setName(): 设置线程名。
     5 
     6 threading模块提供的一些方法:
     7   # threading.currentThread(): 返回当前的线程变量。
     8   # threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
     9   # threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
    10 
    11 from threading import Thread
    12 import threading
    13 from multiprocessing import Process
    14 import os
    15 
    16 def work():
    17     import time
    18     time.sleep(3)
    19     print(threading.current_thread().getName())
    20 
    21 
    22 if __name__ == '__main__':
    23     #在主进程下开启线程
    24     t=Thread(target=work)
    25     t.start()
    26 
    27     print(threading.current_thread().getName())
    28     print(threading.current_thread()) #主线程
    29     print(threading.enumerate()) #连同主线程在内有两个运行的线程
    30     print(threading.active_count())
    31     print('主线程/主进程')
    32 
    33     '''
    34     打印结果:
    35     MainThread
    36     <_MainThread(MainThread, started 140735268892672)>
    37     [<_MainThread(MainThread, started 140735268892672)>, <Thread(Thread-1, started 123145307557888)>]
    38     主线程/主进程
    39     Thread-1
    40     '''
    实例
     1 from threading import Thread
     2 import time
     3 def sayhi(name):
     4     time.sleep(2)
     5     print('%s say hello' %name)
     6 
     7 if __name__ == '__main__':
     8     t=Thread(target=sayhi,args=('egon',))
     9     t.start()
    10     t.join()
    11     print('主线程')
    12     print(t.is_alive())
    13     '''
    14     egon say hello
    15     主线程
    16     False
    17     '''
    join

    守护线程

    无论是进程还是线程,都遵循:守护xx会等待主xx运行完毕后被销毁。需要强调的是:运行完毕并非终止运行

    1 #1.对主进程来说,运行完毕指的是主进程代码运行完毕
    2 #2.对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕
    3 
    4 #1 主进程在其代码结束后就已经算运行完毕了(守护进程在此时就被回收),然后主进程会一直等非守护的子进程都运行完毕后回收子进程的资源(否则会产生僵尸进程),才会结束,
    5 #2 主线程在其他非守护线程运行完毕后才算运行完毕(守护线程在此时就被回收)。因为主线程的结束意味着进程的结束,进程整体的资源都将被回收,而进程必须保证非守护线程都运行完毕后才能结束。
    解释
     1 from threading import Thread
     2 import time
     3 def sayhi(name):
     4     time.sleep(2)
     5     print('%s say hello' %name)
     6 
     7 if __name__ == '__main__':
     8     t=Thread(target=sayhi,args=('egon',))
     9     t.setDaemon(True) #必须在t.start()之前设置
    10     t.start()
    11 
    12     print('主线程')
    13     print(t.is_alive())
    14     '''
    15     主线程
    16     True
    17     '''
    例子1
     1 from threading import Thread
     2 import time
     3 def foo():
     4     print(123)
     5     time.sleep(1)
     6     print("end123")
     7 
     8 def bar():
     9     print(456)
    10     time.sleep(3)
    11     print("end456")
    12 
    13 
    14 t1=Thread(target=foo)
    15 t2=Thread(target=bar)
    16 
    17 t1.daemon=True
    18 t1.start()
    19 t2.start()
    20 print("main-------")
    例子2

     1 from threading import Thread
     2 import os,time
     3 def work():
     4     global n
     5     temp=n
     6     time.sleep(0.1)
     7     n=temp-1
     8 if __name__ == '__main__':
     9     n=100
    10     l=[]
    11     for i in range(100):
    12         p=Thread(target=work)
    13         l.append(p)
    14         p.start()
    15     for p in l:
    16         p.join()
    17 
    18     print(n) #结果可能为99
    多个线程抢占资源
    1 import threading
    2 R=threading.Lock()
    3 R.acquire()
    4 '''
    5 对公共数据的操作
    6 '''
    7 R.release()
     1 from threading import Thread,Lock
     2 import os,time
     3 def work():
     4     global n
     5     lock.acquire()
     6     temp=n
     7     time.sleep(0.1)
     8     n=temp-1
     9     lock.release()
    10 if __name__ == '__main__':
    11     lock=Lock()
    12     n=100
    13     l=[]
    14     for i in range(100):
    15         p=Thread(target=work)
    16         l.append(p)
    17         p.start()
    18     for p in l:
    19         p.join()
    20 
    21     print(n) #结果肯定为0,由原来的并发执行变成串行,牺牲了执行效率保证了数据安全
    同步锁
      1 from threading import Thread,Lock
      2 import os,time
      3 def work():
      4     global n
      5     lock.acquire()
      6     temp=n
      7     time.sleep(0.1)
      8     n=temp-1
      9     lock.release()
     10 if __name__ == '__main__':
     11     lock=Lock()
     12     n=100
     13     l=[]
     14     for i in range(100):
     15         p=Thread(target=work)
     16         l.append(p)
     17         p.start()
     18     for p in l:
     19         p.join()
     20 
     21     print(n) #结果肯定为0,由原来的并发执行变成串行,牺牲了执行效率保证了数据安全
     22 复制代码
     23 
     24 复制代码
     25 #不加锁:并发执行,速度快,数据不安全
     26 from threading import current_thread,Thread,Lock
     27 import os,time
     28 def task():
     29     global n
     30     print('%s is running' %current_thread().getName())
     31     temp=n
     32     time.sleep(0.5)
     33     n=temp-1
     34 
     35 
     36 if __name__ == '__main__':
     37     n=100
     38     lock=Lock()
     39     threads=[]
     40     start_time=time.time()
     41     for i in range(100):
     42         t=Thread(target=task)
     43         threads.append(t)
     44         t.start()
     45     for t in threads:
     46         t.join()
     47 
     48     stop_time=time.time()
     49     print('主:%s n:%s' %(stop_time-start_time,n))
     50 
     51 '''
     52 Thread-1 is running
     53 Thread-2 is running
     54 ......
     55 Thread-100 is running
     56 主:0.5216062068939209 n:99
     57 '''
     58 
     59 
     60 #不加锁:未加锁部分并发执行,加锁部分串行执行,速度慢,数据安全
     61 from threading import current_thread,Thread,Lock
     62 import os,time
     63 def task():
     64     #未加锁的代码并发运行
     65     time.sleep(3)
     66     print('%s start to run' %current_thread().getName())
     67     global n
     68     #加锁的代码串行运行
     69     lock.acquire()
     70     temp=n
     71     time.sleep(0.5)
     72     n=temp-1
     73     lock.release()
     74 
     75 if __name__ == '__main__':
     76     n=100
     77     lock=Lock()
     78     threads=[]
     79     start_time=time.time()
     80     for i in range(100):
     81         t=Thread(target=task)
     82         threads.append(t)
     83         t.start()
     84     for t in threads:
     85         t.join()
     86     stop_time=time.time()
     87     print('主:%s n:%s' %(stop_time-start_time,n))
     88 
     89 '''
     90 Thread-1 is running
     91 Thread-2 is running
     92 ......
     93 Thread-100 is running
     94 主:53.294203758239746 n:0
     95 '''
     96 
     97 #有的同学可能有疑问:既然加锁会让运行变成串行,那么我在start之后立即使用join,就不用加锁了啊,也是串行的效果啊
     98 #没错:在start之后立刻使用jion,肯定会将100个任务的执行变成串行,毫无疑问,最终n的结果也肯定是0,是安全的,但问题是
     99 #start后立即join:任务内的所有代码都是串行执行的,而加锁,只是加锁的部分即修改共享数据的部分是串行的
    100 #单从保证数据安全方面,二者都可以实现,但很明显是加锁的效率更高.
    101 from threading import current_thread,Thread,Lock
    102 import os,time
    103 def task():
    104     time.sleep(3)
    105     print('%s start to run' %current_thread().getName())
    106     global n
    107     temp=n
    108     time.sleep(0.5)
    109     n=temp-1
    110 
    111 
    112 if __name__ == '__main__':
    113     n=100
    114     lock=Lock()
    115     start_time=time.time()
    116     for i in range(100):
    117         t=Thread(target=task)
    118         t.start()
    119         t.join()
    120     stop_time=time.time()
    121     print('主:%s n:%s' %(stop_time-start_time,n))
    122 
    123 '''
    124 Thread-1 start to run
    125 Thread-2 start to run
    126 ......
    127 Thread-100 start to run
    128 主:350.6937336921692 n:0 #耗时是多么的恐怖
    129 '''
    130 
    131
    互斥锁与join

    死锁与递归锁

    进程也有死锁与递归锁,在进程那里忘记说了,放到这里一切说了额

    所谓死锁: 是指两个或两个以上的进程或线程在执行过程中,因争夺资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程,如下就是死锁

    1 from threading import Lock as Lock
    2 import time
    3 mutexA=Lock()
    4 mutexA.acquire()
    5 mutexA.acquire()
    6 print(123)
    7 mutexA.release()
    8 mutexA.release()
    死锁

    解决方法,递归锁,在Python中为了支持在同一线程中多次请求同一资源,python提供了可重入锁RLock。

    这个RLock内部维护着一个Lock和一个counter变量,counter记录了acquire的次数,从而使得资源可以被多次require。直到一个线程所有的acquire都被release,其他的线程才能获得资源。上面的例子如果使用RLock代替Lock,则不会发生死锁:

    1 from threading import RLock as Lock
    2 import time
    3 mutexA=Lock()
    4 mutexA.acquire()
    5 mutexA.acquire()
    6 print(123)
    7 mutexA.release()
    8 mutexA.release()
    递归锁
     1 import time
     2 from threading import Thread,RLock
     3 fork_lock = noodle_lock = RLock()
     4 def eat1(name):
     5     noodle_lock.acquire()
     6     print('%s 抢到了面条'%name)
     7     fork_lock.acquire()
     8     print('%s 抢到了叉子'%name)
     9     print('%s 吃面'%name)
    10     fork_lock.release()
    11     noodle_lock.release()
    12 
    13 def eat2(name):
    14     fork_lock.acquire()
    15     print('%s 抢到了叉子' % name)
    16     time.sleep(1)
    17     noodle_lock.acquire()
    18     print('%s 抢到了面条' % name)
    19     print('%s 吃面' % name)
    20     noodle_lock.release()
    21     fork_lock.release()
    22 
    23 for name in ['哪吒','egon','yuan']:
    24     t1 = Thread(target=eat1,args=(name,))
    25     t2 = Thread(target=eat2,args=(name,))
    26     t1.start()
    27     t2.start()
    科学家吃面

    信号量

    同进程的一样

    Semaphore管理一个内置的计数器,
    每当调用acquire()时内置计数器-1;
    调用release() 时内置计数器+1;
    计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。

    实例:(同时只有5个线程可以获得semaphore,即可以限制最大连接数为5):

     1 from threading import Thread,Semaphore
     2 import threading
     3 import time
     4 # def func():
     5 #     if sm.acquire():
     6 #         print (threading.currentThread().getName() + ' get semaphore')
     7 #         time.sleep(2)
     8 #         sm.release()
     9 def func():
    10     sm.acquire()
    11     print('%s get sm' %threading.current_thread().getName())
    12     time.sleep(3)
    13     sm.release()
    14 if __name__ == '__main__':
    15     sm=Semaphore(5)
    16     for i in range(23):
    17         t=Thread(target=func)
    18         t.start()
    例子
    1 与进程池是完全不同的概念,进程池Pool(4),最大只能产生4个进程,而且从头到尾都只是这四个进程,不会产生新的,而信号量是产生一堆线程/进程
    池与信号量

    事件

    同进程的一样

    线程的一个关键特性是每个线程都是独立运行且状态不可预测。如果程序中的其 他线程需要通过判断某个线程的状态来确定自己下一步的操作,这时线程同步问题就会变得非常棘手。为了解决这些问题,我们需要使用threading库中的Event对象。 对象包含一个可由线程设置的信号标志,它允许线程等待某些事件的发生。在 初始情况下,Event对象中的信号标志被设置为假。如果有线程等待一个Event对象, 而这个Event对象的标志为假,那么这个线程将会被一直阻塞直至该标志为真。一个线程如果将一个Event对象的信号标志设置为真,它将唤醒所有等待这个Event对象的线程。如果一个线程等待一个已经被设置为真的Event对象,那么它将忽略这个事件, 继续执行

    1 event.isSet():返回event的状态值;
    2 event.wait():如果 event.isSet()==False将阻塞线程;
    3 event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;
    4 event.clear():恢复event的状态值为False。
     1 import threading
     2 import time,random
     3 from threading import Thread,Event
     4 
     5 def conn_mysql():
     6     count=1
     7     while not event.is_set():
     8         if count > 3:
     9             raise TimeoutError('链接超时')
    10         print('<%s>第%s次尝试链接' % (threading.current_thread().getName(), count))
    11         event.wait(0.5)
    12         count+=1
    13     print('<%s>链接成功' %threading.current_thread().getName())
    14 
    15 
    16 def check_mysql():
    17     print('33[45m[%s]正在检查mysql33[0m' % threading.current_thread().getName())
    18     time.sleep(random.randint(2,4))
    19     event.set()
    20 if __name__ == '__main__':
    21     event=Event()
    22     conn1=Thread(target=conn_mysql)
    23     conn2=Thread(target=conn_mysql)
    24     check=Thread(target=check_mysql)
    25 
    26     conn1.start()
    27     conn2.start()
    28     check.start()
    例子

    条件

    使得线程等待,只有满足某条件时,才释放n个线程

    1 Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。
    解释
     1 import threading
     2 
     3 def run(n):
     4     con.acquire()
     5     con.wait()
     6     print("run the thread: %s" % n)
     7     con.release()
     8 
     9 if __name__ == '__main__':
    10 
    11     con = threading.Condition()
    12     for i in range(10):
    13         t = threading.Thread(target=run, args=(i,))
    14         t.start()
    15 
    16     while True:
    17         inp = input('>>>')
    18         if inp == 'q':
    19             break
    20         con.acquire()
    21         con.notify(int(inp))
    22         con.release()
    23         print('****')
    例子

    定时器

    定时器,指定n秒后执行某个操作

    1 from threading import Timer
    2  
    3 def hello():
    4     print("hello, world")
    5  
    6 t = Timer(1, hello)
    7 t.start()  # after 1 seconds, "hello, world" will be printed

    线程队列

     1 import queue
     2 
     3 q=queue.Queue()
     4 q.put('first')
     5 q.put('second')
     6 q.put('third')
     7 
     8 print(q.get())
     9 print(q.get())
    10 print(q.get())
    11 '''
    12 结果(先进先出):
    13 first
    14 second
    15 third
    16 '''
    先进先出
     1 import queue
     2 
     3 q=queue.LifoQueue()
     4 q.put('first')
     5 q.put('second')
     6 q.put('third')
     7 
     8 print(q.get())
     9 print(q.get())
    10 print(q.get())
    11 '''
    12 结果(后进先出):
    13 third
    14 second
    15 first
    16 '''
    后进先出
     1 import queue
     2 
     3 q=queue.PriorityQueue()
     4 #put进入一个元组,元组的第一个元素是优先级(通常是数字,也可以是非数字之间的比较),数字越小优先级越高
     5 q.put((20,'a'))
     6 q.put((10,'b'))
     7 q.put((30,'c'))
     8 
     9 print(q.get())
    10 print(q.get())
    11 print(q.get())
    12 '''
    13 结果(数字越小优先级越高,优先级高的优先出队):
    14 (10, 'b')
    15 (20, 'a')
    16 (30, 'c')
    17 '''
    优先级

    Python标准模块--concurrent.futures

     1 #1 介绍
     2 concurrent.futures模块提供了高度封装的异步调用接口
     3 ThreadPoolExecutor:线程池,提供异步调用
     4 ProcessPoolExecutor: 进程池,提供异步调用
     5 Both implement the same interface, which is defined by the abstract Executor class.
     6 
     7 #2 基本方法
     8 #submit(fn, *args, **kwargs)
     9 异步提交任务
    10 
    11 #map(func, *iterables, timeout=None, chunksize=1) 
    12 取代for循环submit的操作
    13 
    14 #shutdown(wait=True) 
    15 相当于进程池的pool.close()+pool.join()操作
    16 wait=True,等待池内所有任务执行完毕回收完资源后才继续
    17 wait=False,立即返回,并不会等待池内的任务执行完毕
    18 但不管wait参数为何值,整个程序都会等到所有任务执行完毕
    19 submit和map必须在shutdown之前
    20 
    21 #result(timeout=None)
    22 取得结果
    23 
    24 #add_done_callback(fn)
    25 回调函数
     1 #介绍
     2 The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.
     3 
     4 class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None)
     5 An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised.
     6 
     7 
     8 #用法
     9 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
    10 
    11 import os,time,random
    12 def task(n):
    13     print('%s is runing' %os.getpid())
    14     time.sleep(random.randint(1,3))
    15     return n**2
    16 
    17 if __name__ == '__main__':
    18 
    19     executor=ProcessPoolExecutor(max_workers=3)
    20 
    21     futures=[]
    22     for i in range(11):
    23         future=executor.submit(task,i)
    24         futures.append(future)
    25     executor.shutdown(True)
    26     print('+++>')
    27     for future in futures:
    28         print(future.result())
    ProcessPoolExecutor
     1 #介绍
     2 ThreadPoolExecutor is an Executor subclass that uses a pool of threads to execute calls asynchronously.
     3 class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='')
     4 An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.
     5 
     6 Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor.
     7 
     8 New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging.
     9 
    10 #用法
    11 与ProcessPoolExecutor相同
    ThreadPoolExecutor
     1 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
     2 
     3 import os,time,random
     4 def task(n):
     5     print('%s is runing' %os.getpid())
     6     time.sleep(random.randint(1,3))
     7     return n**2
     8 
     9 if __name__ == '__main__':
    10 
    11     executor=ThreadPoolExecutor(max_workers=3)
    12 
    13     # for i in range(11):
    14     #     future=executor.submit(task,i)
    15 
    16     executor.map(task,range(1,12)) #map取代了for+submit
    map
     1 from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor
     2 from multiprocessing import Pool
     3 import requests
     4 import json
     5 import os
     6 
     7 def get_page(url):
     8     print('<进程%s> get %s' %(os.getpid(),url))
     9     respone=requests.get(url)
    10     if respone.status_code == 200:
    11         return {'url':url,'text':respone.text}
    12 
    13 def parse_page(res):
    14     res=res.result()
    15     print('<进程%s> parse %s' %(os.getpid(),res['url']))
    16     parse_res='url:<%s> size:[%s]
    ' %(res['url'],len(res['text']))
    17     with open('db.txt','a') as f:
    18         f.write(parse_res)
    19 
    20 
    21 if __name__ == '__main__':
    22     urls=[
    23         'https://www.baidu.com',
    24         'https://www.python.org',
    25         'https://www.openstack.org',
    26         'https://help.github.com/',
    27         'http://www.sina.com.cn/'
    28     ]
    29 
    30     # p=Pool(3)
    31     # for url in urls:
    32     #     p.apply_async(get_page,args=(url,),callback=pasrse_page)
    33     # p.close()
    34     # p.join()
    35 
    36     p=ProcessPoolExecutor(3)
    37     for url in urls:
    38         p.submit(get_page,url).add_done_callback(parse_page) #parse_page拿到的是一个future对象obj,需要用obj.result()拿到结果
    回调函数
  • 相关阅读:
    NFC Basics(基本NFC)——翻译自developer.android.com
    【LeetCode】Sort Colors 解题报告
    发送手机物理标识请求
    Java编程介绍
    emacs 中使用git diff命令行
    OpenJudge百炼习题解答(C++)--题4074:积水量
    编程之美2.9 斐波那契数列
    Application Architecture Determines Application Performance
    程序包javax.servlet.annotation不存在
    mysql 严格模式 Strict Mode说明
  • 原文地址:https://www.cnblogs.com/xiaobin12126/p/8689217.html
Copyright © 2020-2023  润新知