python任務執行之線程,進程,與協程,python

來源:互聯網
上載者:User

python任務執行之線程,進程,與協程,python

一、線程

  線程為程式中執行任務的最小單元,由Threading模組提供了相關操作,線程適合於IO操作密集的情況下使用

1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import threading 4 import time 5 6 def show(arg): 7 time.sleep(1) 8 print 'thread'+str(arg) 9 10 for i in range(10):11 t = threading.Thread(target=show, args=(i,))12 t.start()13 14 print 'main thread stop'線程基本使用

上述代碼建立了10個“前台”線程,然後控制器就交給了CPU,CPU根據指定演算法進行調度,分區執行指令。

更多操作如下

1 start 線程準備就緒,等待CPU調度2 setName 為線程設定名稱3 getName 擷取線程名稱4 setDaemon 設定為後台線程或前台線程(預設)5 如果是後台線程,主線程執行過程中,後台線程也在進行,主線程執行完畢後,後台線程不論成功與否,均停止6 如果是前台線程,主線程執行過程中,前台線程也在進行,主線程執行完畢後,等待前台線程也執行完成後,程式停止7 join 逐個執行每個線程,執行完畢後繼續往下執行,該方法使得多線程變得無意義8 run 線程被cpu調度後自動執行線程對象的run方法View Codeimport threadingimport 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()自訂線程類

 由於線程之間是進行隨機調度,並且每個線程可能只執行n條執行之後,當多個線程同時修改同一條資料時可能會出現混亂資料,所以,出現了線程鎖 - 同一時刻允許一個線程執行操作。使用代碼方法如下

1 #!/usr/bin/env python 2 #coding:utf-8 3 4 import threading 5 import time 6 7 gl_num = 0 8 9 lock = threading.RLock()#定義鎖10 11 def Func():12 lock.acquire()#使用鎖13 global gl_num14 gl_num +=115 time.sleep(1)16 print gl_num17 lock.release()#操作完畢,解鎖18 19 for i in range(10):20 t = threading.Thread(target=Func)21 t.start()View Code

 

互斥鎖 同時只允許一個線程更改資料,而Semaphore是同時允許一定數量的線程更改資料 ,比如廁所有3個坑,那最多隻允許3個人上廁所,後面的人只能等裡面有人出來了才能再進去。

1 import threading,time 2 3 def run(n): 4 semaphore.acquire() 5 time.sleep(1) 6 print("run the thread: %s" %n) 7 semaphore.release() 8 9 if __name__ == '__main__':10 11 num= 012 semaphore = threading.BoundedSemaphore(5) #最多允許5個線程同時運行13 for i in range(20):14 t = threading.Thread(target=run,args=(i,))15 t.start()互拆鎖

線程的事件(event)

python線程的事件用於主線程式控制制其他線程的執行,事件主要提供了三個方法 set、wait、clear。

事件處理的機制:全域定義了一個“Flag”,如果“Flag”值為 False,那麼當程式執行 event.wait 方法時就會阻塞,如果“Flag”值為True,那麼event.wait 方法時便不再阻塞。

  • clear:將“Flag”設定為False
  • set:將“Flag”設定為True
#!/usr/bin/env python# -*- coding:utf-8 -*- import threading def do(event): print 'start' event.wait() print 'execute' event_obj = threading.Event()for i in range(10): t = threading.Thread(target=do, args=(event_obj,)) t.start() event_obj.clear()inp = raw_input('input:')if inp == 'true': event_obj.set()event執行個體

條件,使線程等待,只有條件滿足才釋放n個線程

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()View Code

 

Timer定時器,指定n秒之後執行操作

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

二、進程

  進程的建立會耗費記憶體的空間,謹慎建立,多進程適用於計算密集型的情況適用

from threading import Timer def hello(): print("hello, world") t = Timer(1, hello)t.start() # after 1 seconds, "hello, world" will be printed進程的基本使用

進程預設情況下的資料不是共用的(線程共用記憶體資料),所以開銷比較大,預設無法共用資料

#!/usr/bin/env python#coding:utf-8 from multiprocessing import Processfrom 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預設無法共用資料#方法一,Arrayfrom multiprocessing import Process,Arraytemp = 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, queuesimport multiprocessingdef f(i, q): print(i, q.get())if __name__ == '__main__': q = queues.Queue(ctx=multiprocessing) q.put('h1') q.put('h2') q.put('h3') for i in range(3): p = Process(target=f, args=(i, q, )) p.start()通過隊列實現資料共用

 

當建立進程時(非使用時),共用資料會被拿到子進程中,當進程中執行完畢後,再賦值給原值。因此進程也是有鎖的

#!/usr/bin/env python# -*- coding:utf-8 -*-from multiprocessing import Process, Array, RLockdef 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
#!/usr/bin/env python# -*- coding:utf-8 -*-from multiprocessing import Process,Poolimport 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

apply_async是非阻塞的,apply、是阻塞的,而且apply_async多一個參數,為回呼函數

更多方法

•close() 關閉pool,使其不在接受新的任務。•terminate() 結束背景工作處理序,不在處理未完成的任務。•join() 主進程阻塞,等待子進程的退出, join方法要在close或terminate之後使用。View Code

三、協程

線程和進程的操作是由程式觸發系統介面,最後的執行者是系統;協程的操作則是程式員。

協程存在的意義:對於多線程應用,CPU通過切片的方式來切換線程間的執行,線程切換時需要耗時(儲存狀態,下次繼續)。協程,則只使用一個線程,在一個線程中規定某個代碼塊執行順序。

協程的適用情境:當程式中存在大量不需要CPU的操作時(IO),適用於協程,簡單的說就是將線程的執行的任務進行了最佳化,切片執行,比如一個線程在做一個網路請求的時候就會有延遲,這段時間軸程是等待的,協成用這等待的時間去做別的

基本協程模組

#!/usr/bin/env python# -*- coding:utf-8 -*- 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()greenlet

封裝比較完善的協成模組 

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),])gevett

遇到IO自動切換

from gevent import monkey; monkey.patch_all()import geventimport urllib2def 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/'),])View Code

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.