Python之美[從菜鳥到高手]--threading daemon線程原理解讀,python--threading

來源:互聯網
上載者:User

Python之美[從菜鳥到高手]--threading daemon線程原理解讀,python--threading

事情的起因是我在看下面一段代碼遇到的疑惑,明明是while True,為什麼代碼沒有死迴圈??

class D(threading.Thread):    def __init__(self, queue):        threading.Thread.__init__(self)        self.queue = queue    def run(self):        while  True:            url = self.queue.get()            self.download_file(url)            self.queue.task_done()    def download_file(self, url):        h = urllib2.urlopen(url)        f = os.path.basename(url)+'.html'        with open(f,'wb') as f:            while  True:                c = h.read(1024)                if not c:                    break                f.write(c)if __name__ == "__main__":    urls= ['http://www.baidu.com','http://www.sina.com']    queue = Queue.Queue()    for i in range(5):        t = D(queue)        t.setDaemon(True)        t.start()    for u in urls:        queue.put(u)    queue.join()

之前前一直簡單認為setDaemon就是設定為後台線程而已,沒有進一步去挖掘裡面的含義。

可問題的關鍵就是setDaemon,在底層的thread模組中,只要主線程結束了,所有的其它線程都會結束,這很明顯,主線程結束python將銷毀運行時環境,主線程肯定會被結束。所以threading模組的線程setDaemon就是

為瞭解決這個問題的,如果setDaemon(True),那麼和之前一樣,主線程結束,所有子線程都將結束。

如果setDaemon(False),主線程將等待該線程結束,等同於你調用線程的join方法。

所以如果將上面的setDaemon注釋和修改為True,那麼程式將死迴圈。

其實我們並不推薦上面的做法,上面做法有點線程池的味道,但如果你看過一些python的線程池實現,while True

迴圈中肯定有檢測退出語句,因為在python的世界裡言明比隱晦更加pythonic。但很不幸的是,上面的代碼就來

自與<<編寫高品質代碼:改善Python程式的91個建議>>,我並沒有噴這本書,但我覺得代碼舉例的確有待商榷。

你可能好奇,setDaemon(False)是如何等同於線程join的呢?,不急,且聽我慢慢道來。

未解決這個問題,threading模組引入了_MainThread對象

# Special thread class to represent the main thread# This is garbage collected through an exit handlerclass _MainThread(Thread):    def __init__(self):        Thread.__init__(self, name="MainThread")        self._Thread__started.set()        self._set_ident()        with _active_limbo_lock:            _active[_get_ident()] = self    def _set_daemon(self):        return False    def _exitfunc(self):        self._Thread__stop()        t = _pickSomeNonDaemonThread()        if t:            if __debug__:                self._note("%s: waiting for other threads", self)        while t:            t.join()            t = _pickSomeNonDaemonThread()        if __debug__:            self._note("%s: exiting", self)        self._Thread__delete()def _pickSomeNonDaemonThread():    for t in enumerate():        if not t.daemon and t.is_alive():            return t    return None# Create the main thread object,# and make it available for the interpreter# (Py_Main) as threading._shutdown._shutdown = _MainThread()._exitfunc
其實_MainThread並沒有幹什麼事,唯一的貢獻就是在threading模組匯入時建立了一個執行個體,並將_exitfunc
賦值給_shutdown函數。_exitfunc將收集所有非daemon且alive的線程,並調用線程的join方法。哦,原來是

_MainThread悄悄的在幕後奮鬥著,剩下的問題就是誰調用_shutdown函數的呢?

當python要銷毀運行時之前肯定會調用,所以開啟pythonrun.c,你會發現如下函數

/* Wait until threading._shutdown completes, provided   the threading module was imported in the first place.   The shutdown routine will wait until all non-daemon   "threading" threads have completed. */static voidwait_for_thread_shutdown(void){#ifdef WITH_THREAD    PyObject *result;    PyThreadState *tstate = PyThreadState_GET();    PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,                                                  "threading");    if (threading == NULL) {        /* threading not imported */        PyErr_Clear();        return;    }    result = PyObject_CallMethod(threading, "_shutdown", "");    if (result == NULL)        PyErr_WriteUnraisable(threading);    else        Py_DECREF(result);    Py_DECREF(threading);#endif}
原來是這傢伙在搞鬼,漲見識了,原來在C中還有調用py代碼的需求啊。沒辦法啊,誰讓threading模組是純py
代碼呢!!!




python編程中線程結束的問題

def _exitCheckfunc(): print "ok" try: while 1: alive=False if thread_.isAlive(): alive=True if not alive: break time.sleep(1) #為了使得統計時間能夠運行,要捕捉 KeyboardInterrupt :ctrl-c except KeyboardInterrupt, e: traceback.print_exc() print "consume time :",time.time()-start threading._shutdown=_exitCheckfunc自己在主線程中寫一個死迴圈來接受ctrl+c的訊號。
或者用進程監控 :
code.activestate.com/...-prog/

 
python threading模組,產生多線程之後,怎得到線程執行完成後return出的字串?

多線程/多進程都是通訊或者回調,而不是直接返回結果。這個很容易理解的,因為如果你用返回結果來給一個變數賦值,你就必須等待這個函數結束,你這個程式就阻塞了,這就失去了多線程/多進程防止阻塞的意義了。
通訊可以是事件驅動或者用安全執行緒的資料結構來傳遞資料(比如Queue,也可以是訊息佇列0mq,rabbitMQ之類),回調就是你一個程式執行完成後調用另外一個函數來處理接下來怎麼做。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.