• Python之线程与进程


    1.程序

    程序指的是指令的集合;程序不能单独的运行,必须将程序装载在内存中,系统给它分配资源才可以运行。

    程序是进程动态运行的静态描述文本

    2.进程

    进程指的是程序在数据集中一次动态运行的过程;

    优点:同时利用多个cpu,能够同时进行多个操作
    缺点:耗费资源(重新开辟内存空间)

    3.线程

    线程进程的最小执行单位,真正在CPU运行的是线程

    优点:共享内存,IO操作的时候,创造并发操作
    缺点:抢占资源

    4.进程与线程的关系

    一个线程只能在一个进程里面,一个进程可以包含多个线程; 进程是资源管理单位(容器)  线程是最小执行单位

    5.并行与并发

    并行:指的是同时处理多个任务(多个线程被不同的CPU执行)

    并发:指的是交替处理多个任务(多个线程被一个CPU执行)

    6.同步与异步

    同步:请求数据的时候,如果被请求方没有返回数据,那么程序就会一直等下去,不会执行下面的操作,直到接收到返回的数据。(单线程)

    异步:不会等下去,而是直接执行下面的操作,如果有数据返回,那么系统会通知进程去处理(多线程)

    这些知识概念的性的知识,现在开始了解下线程和进程吧!

    线程:threading模块

    import time
    import threading
    
    def f1():
        print(11)
    
    def f2(a1,a2):
        time.sleep(10)
        print(a1,a2)
        f1()
    
    t=threading.Thread(target=f2,args=(22,33))
    t.start()
    
    t=threading.Thread(target=f2,args=(44,55))
    t.start()
    
    t=threading.Thread(target=f2,args=(66,77))
    t.start()

    上面代码创建了3个前台线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。

    更多方法:

      • start            线程准备就绪,等待CPU调度
      • setName      为线程设置名称
      • getName      获取线程名称
      • setDaemon   设置为后台线程或前台线程(默认为False)
                           如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,均停止(设置为True)
                            如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,程序停止
      • join              逐个执行每个线程,执行完毕后继续往下执行,该方法使得多线程变得无意义
      • run              线程被cpu调度后自动执行线程对象的run方法
    import threading
    import time
     
     
    class MyThread(threading.Thread):
        def __init__(self,num):
            threading.Thread.__init__(self)
            self.num = num
     
        def run(self):#定义每个线程要运行的函数
     
            print("running on number:%s" %self.num)
     
            time.sleep(3)
     
    if __name__ == '__main__':
     
        t1 = MyThread(1)
        t2 = MyThread(2)
        t1.start()
        t2.start()
    自定义线程类

    线程锁(Lock、RLock)

    由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,当多个线程同时修改同一条数据时可能会出现脏数据,所以,出现了线程锁 - 同一时刻允许一个线程执行操作。

    import threading
    import time
    
    gl_num = 0
    
    def show(arg):
        global gl_num
        time.sleep(1)
        gl_num +=1
        print gl_num
    
    for i in range(10):
        t = threading.Thread(target=show, args=(i,))
        t.start()
    
    print 'main thread stop'
    未使用锁
    import threading
    import time
       
    gl_num = 0
       
    lock = threading.RLock()
       
    def Func():
        lock.acquire()
        global gl_num
        gl_num +=1
        time.sleep(1)
        print gl_num
        lock.release()
           
    for i in range(10):
        t = threading.Thread(target=Func)
        t.start()

    信号量(Semaphore)

    互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。

    import threading,time
     
    def run(n):
        semaphore.acquire()
        time.sleep(1)
        print("run the thread: %s" %n)
        semaphore.release()
     
    if __name__ == '__main__':
     
        num= 0
        semaphore  = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
        for i in range(20):
            t = threading.Thread(target=run,args=(i,))
            t.start()

    事件(event)

    python线程的事件用于主线程控制其他线程的执行,事件主要提供了三个方法 set、wait、clear。

    事件处理的机制:全局定义了一个“Flag”,如果“Flag”值为 False,那么当程序执行 event.wait 方法时就会阻塞,如果“Flag”值为True,那么event.wait 方法时便不再阻塞。

    • clear:将“Flag”设置为False
    • set:将“Flag”设置为True
    import threading
     
    def run(n):
        con.acquire()
        con.wait()
        print("run the thread: %s" %n)
        con.release()
     
    if __name__ == '__main__':
     
        con = threading.Condition()
        for i in range(10):
            t = threading.Thread(target=run, args=(i,))
            t.start()
     
        while True:
            inp = input('>>>')
            if inp == 'q':
                break
            con.acquire()
            con.notify(int(inp))
            con.release()
     
    def condition_func():
    
        ret = False
        inp = input('>>>')
        if inp == '1':
            ret = True
    
        return ret
    
    
    def run(n):
        con.acquire()
        con.wait_for(condition_func)
        print("run the thread: %s" %n)
        con.release()
    
    if __name__ == '__main__':
    
        con = threading.Condition()
        for i in range(10):
            t = threading.Thread(target=run, args=(i,))
            t.start()

    Timer

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

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

     进程

    from multiprocessing import Process
    import threading
    import time
      
    def foo(i):
        print 'say hi',i
      
    for i in range(10):
        p = Process(target=foo,args=(i,))
        p.start()

    注意:由于进程之间的数据需要各自持有一份,所以创建进程需要的非常大的开销。

    进程数据共享

    进程各自持有一份数据,默认无法共享数据

    #!/usr/bin/env python
    #coding:utf-8
     
    from multiprocessing import Process
    from multiprocessing import Manager
     
    import time
     
    li = []
     
    def foo(i):
        li.append(i)
        print 'say hi',li
      
    for i in range(10):
        p = Process(target=foo,args=(i,))
        p.start()
         
    print 'ending',li
    进程间默认无法数据共享
    #方法一,Array
    from multiprocessing import Process,Array
    temp = Array('i', [11,22,33,44])
     
    def Foo(i):
        temp[i] = 100+i
        for item in temp:
            print i,'----->',item
     
    for i in range(2):
        p = Process(target=Foo,args=(i,))
        p.start()
     
    #方法二:manage.dict()共享数据
    from multiprocessing import Process,Manager
     
    manage = Manager()
    dic = manage.dict()
     
    def Foo(i):
        dic[i] = 100+i
        print dic.values()
     
    for i in range(2):
        p = Process(target=Foo,args=(i,))
        p.start()
        p.join()
    复制代码
    
        'c': ctypes.c_char,  'u': ctypes.c_wchar,
        'b': ctypes.c_byte,  'B': ctypes.c_ubyte,
        'h': ctypes.c_short, 'H': ctypes.c_ushort,
        'i': ctypes.c_int,   'I': ctypes.c_uint,
        'l': ctypes.c_long,  'L': ctypes.c_ulong,
        'f': ctypes.c_float, 'd': ctypes.c_double
    
    复制代码
    类型对应表
    from multiprocessing import Process, Queue
    
    def f(i,q):
        print(i,q.get())
    
    if __name__ == '__main__':
        q = Queue()
    
        q.put("h1")
        q.put("h2")
        q.put("h3")
    
        for i in range(10):
            p = Process(target=f, args=(i,q,))
            p.start()
    View Code

    当创建进程时(非使用时),共享数据会被拿到子进程中,当进程中执行完毕后,再赋值给原值。

    from multiprocessing import Process, Array, RLock
    
    def Foo(lock,temp,i):
        """
        将第0个数加100
        """
        lock.acquire()
        temp[0] = 100+i
        for item in temp:
            print i,'----->',item
        lock.release()
    
    lock = RLock()
    temp = Array('i', [11, 22, 33, 44])
    
    for i in range(20):
        p = Process(target=Foo,args=(lock,temp,i,))
        p.start()
    进程锁实例

    进程池

    进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。

    进程池中有两个方法:

    • apply
    • apply_async
    from  multiprocessing import Process,Pool
    import time
      
    def Foo(i):
        time.sleep(2)
        return i+100
      
    def Bar(arg):
        print arg
      
    pool = Pool(5)
    #print pool.apply(Foo,(1,))
    #print pool.apply_async(func =Foo, args=(1,)).get()
      
    for i in range(10):
        pool.apply_async(func=Foo, args=(i,),callback=Bar)
      
    print 'end'
    pool.close()
    pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
    View Code

    协程

    线程和进程的操作是由程序触发系统接口,最后的执行者是系统;协程的操作则是程序员。

    协程存在的意义:对于多线程应用,CPU通过切片的方式来切换线程间的执行,线程切换时需要耗时(保存状态,下次继续)。协程,则只使用一个线程,在一个线程中规定某个代码块执行顺序。

    协程的适用场景:当程序中存在大量不需要CPU的操作时(IO),适用于协程;

    greenlet

    from greenlet import greenlet
     
     
    def test1():
        print 12
        gr2.switch()
        print 34
        gr2.switch()
     
     
    def test2():
        print 56
        gr1.switch()
        print 78
     
    gr1 = greenlet(test1)
    gr2 = greenlet(test2)
    gr1.switch()

    gevent

    import gevent
     
    def foo():
        print('Running in foo')
        gevent.sleep(0)
        print('Explicit context switch to foo again')
     
    def bar():
        print('Explicit context to bar')
        gevent.sleep(0)
        print('Implicit context switch back to bar')
     
    gevent.joinall([
        gevent.spawn(foo),
        gevent.spawn(bar),
    ])

    遇到IO操作自动切换:

    from gevent import monkey; monkey.patch_all()
    import gevent
    import urllib2
    
    def f(url):
        print('GET: %s' % url)
        resp = urllib2.urlopen(url)
        data = resp.read()
        print('%d bytes received from %s.' % (len(data), url))
    
    gevent.joinall([
            gevent.spawn(f, 'https://www.python.org/'),
            gevent.spawn(f, 'https://www.yahoo.com/'),
            gevent.spawn(f, 'https://github.com/'),
    ])

    queue模块

    Queue 就是队列,它是线程安全的

     队列的特性:先进先出

    import queue
    
    q = queue.Queue(maxsize=0)  #构造一个先进先出的队列,maxsize指定队列长度,为0时,表示队列长度无限。
    
    q.join()  #等到队列为None的时候,再执行别的操作
    q.qsize()  #返回队列的大小(不可靠)
    q.empty()  #当队列为空的时候,返回True 否则返回False(不可靠)
    q.full()  #当队列满的时候,返回True,否则返回False(不可靠)
    
    
    q.put(item, block=True, timeout=None)  #将item放入Queue尾部,item必须存在,可以参数block默认为True,表示当队列满时,会等待队列给出可用位置
                                           #为Flase时为非阻塞,此时如果队列已经满,会引发queue.Full异常。可以选参数timeout,表示会阻塞的时间,
                                           #如果队列无法给出放入item的位置,则引发queue.Full异常。
    q.get(block=True, timeout=None)  #等  移除并返回队列头部的一个值,可选参数block默认为True,表示获取值的时候,如果队列为空,则阻塞,为False时,不阻塞,
                                       #若此时队列为空,则引发 queue.Empty异常。可选参数timeout,表示会阻塞设置的时候,过后,如果队列为空,则引发Empty异常。
    q.put_nowait(item)  #等效put(item,block=False)
    q.get_nowait()  #不等   等效于 get(item,block=False)
    生产者,消费者

    生产者将数据依次存入队列,消费者依次从队列中取出数据。

    实例

    import queue
    import threading
    
    message = queue.Queue(10)
    
    def producer(i):
        while True:
            message.put(i)
    
    def consumer(i):
        while True:
            msg = message.get()
            print(msg)
    
    for i in range(12):
        t = threading.Thread(target=producer, args=(i,))
        t.start()
    
    for i in range(10):
        t = threading.Thread(target=consumer, args=(i,))
        t.start()
  • 相关阅读:
    数据字典/动态性能视图
    参数管理
    expdp实现oracle远程服务器导出到本地
    jquery 操作单选按钮
    vs2012加载T4MVC模板
    Asp.net Mvc 过滤器执行顺序
    oracle版本及字符集查询
    ora-01658: 无法为表空间*****中的段创建 INITIAL 区
    SmtpClient发送邮件
    盒模型padding和margin对滚动条位置的影响
  • 原文地址:https://www.cnblogs.com/wangbinbin/p/7420850.html
Copyright © 2020-2023  润新知