zoukankan      html  css  js  c++  java
  • python day10

    Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import threading
    import time
      
    def show(arg):
        time.sleep(1)
        print 'thread'+str(arg)
      
    for i in range(10):
        t = threading.Thread(target=show, args=(i,))
        t.start()
      
    print 'main thread stop'
    

      

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

    更多方法:

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

        线程锁(Lock、RLock)

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

      •  1 复制代码
         2 #!/usr/bin/env python
         3 # -*- coding:utf-8 -*-
         4 import threading
         5 import time
         6 
         7 gl_num = 0
         8 
         9 def show(arg):
        10     global gl_num
        11     time.sleep(1)
        12     gl_num +=1
        13     print gl_num
        14 
        15 for i in range(10):
        16     t = threading.Thread(target=show, args=(i,))
        17     t.start()
        18 
        19 print 'main thread stop'
        20 复制代码
        21 1
        22 2
        23 3
        24 4
        25 5
        26 6
        27 7
        28 8
        29 9
        30 10
        31 11
        32 12
        33 13
        34 14
        35 15
        36 16
        37 17
        38 18
        39 19
        40 20
        41 21
        42 #!/usr/bin/env python
        43 #coding:utf-8
        44    
        45 import threading
        46 import time
        47    
        48 gl_num = 0
        49    
        50 lock = threading.RLock()
        51    
        52 def Func():
        53     lock.acquire()
        54     global gl_num
        55     gl_num +=1
        56     time.sleep(1)
        57     print gl_num
        58     lock.release()
        59        
        60 for i in range(10):
        61     t = threading.Thread(target=Func)
        62     t.start()
        63 信号量(Semaphore)
        64 
        65 互斥锁 同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,比如厕所有3个坑,那最多只允许3个人上厕所,后面的人只能等里面有人出来了才能再进去。
        66 
        67 1
        68 2
        69 3
        70 4
        71 5
        72 6
        73 7
        74 8
        75 9
        76 10
        77 11
        78 12
        79 13
        80 14
        81 15
        82 import threading,time
        83  
        84 def run(n):
        85     semaphore.acquire()
        86     time.sleep(1)
        87     print("run the thread: %s" %n)
        88     semaphore.release()
        89  
        90 if __name__ == '__main__':
        91  
        92     num= 0
        93     semaphore  = threading.BoundedSemaphore(5) #最多允许5个线程同时运行
        94     for i in range(20):
        95         t = threading.Thread(target=run,args=(i,))
        96         t.start()
        未使用锁
        #!/usr/bin/env python
        #coding:utf-8
           
        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()
        

          

        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
        Python 进程
        

          Python 进程

      • 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()
        

          select

      • #!/usr/bin/env python
        #-*-coding:utf-8-*
        import socket,select
        sk = socket.socket()
        sk.bind(('127.0.0.1',9999))
        sk.listen(5)
        inputs = [sk,] #sk服务端socket
        outputs = []
        message = {}
        while True:
            rlist,wlist,e = select.select(inputs,outputs,[],1)
            print (len(inputs),len(rlist),len(wlist))
            for i in rlist:
                if i ==sk:
                    conn,addre = i.accept()
                    #conn其实是socket对象
                    inputs.append(conn)
                    message[conn] = []
                    #conn.sendall(bytes('hello',encoding='utf-8'))
                else:
                    #有人给我发消息了
                    try:
                       ret = i.recv(1024)
                       if not ret:
                           raise Exception('断开连接')
                       else:
                           outputs.append(i)
                           message[i].append(ret)
                    except Exception as e:
                        inputs.remove(i)
                        del message[i]
            #所有给我发过消息的人
            for w in wlist:
                msg = message[w].pop()
                resp = msg + bytes('+response',encoding='utf-8')
                w.sendall(resp)
                outputs.remove(w)
        

          

  • 相关阅读:
    【leetcode_easy】589. N-ary Tree Preorder Traversal
    【linux基础】Ubuntu下的终端多标签切换快捷键
    车道线检测github集锦
    [c++]struct timeval
    [opencv] copyTo函数的使用方法
    [c++]C++关键字之friend
    【动手学深度学习】Jupyter notebook中 import mxnet出错
    【opencv】split
    【leetcode_easy】581. Shortest Unsorted Continuous Subarray
    第1课 学习Lua的意义
  • 原文地址:https://www.cnblogs.com/zl-py/p/5675753.html
Copyright © 2011-2022 走看看