python day10

Threading用於提供線程相關的操做,線程是應用程序中工做的最小單元。python

#!/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)app

      因爲線程之間是進行隨機調度,而且每一個線程可能只執行n條執行以後,當多個線程同時修改同一條數據時可能會出現髒數據,因此,出現了線程鎖 - 同一時刻容許一個線程執行操做。socket

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

        

      Timeride

      定時器,指定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 進程ui

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

        selectspa

    • #!/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)
      
相關文章
相關標籤/搜索