python 多進程與多線程淺析

來源:互聯網
上載者:User

標籤:python   thread   pool   process   gil   

python多線程是偽多線程,同時間最多隻有一個線程在執行,但這樣並不代碼python的多線程沒有作用,對於IO密集型的系統,python的多線程還是能極大的提升效能~

關於python偽多線程可以去瞭解python GIL的概念。

以下代碼涉及python多線程,多進程,進程池相關操作:

#encoding:utf-8from multiprocessing import Pool,Manager,cpu_count,Lock,Processimport threadimport threadingdef process_fun(msg):print 'process_fun msg:', msgpassdef thread_fun(msg):print 'thread_fun msg:', msgpassif __name__ == '__main__':msg = 'hello world';#啟動一個子進程msg = "is process"child_proc = Process(target=process_fun, args=(msg,))child_proc.start() #啟動一個線程 使用thread模組msg = "is thread using thread module"thread.start_new_thread(thread_fun, (msg,)) #啟動一個線程 使用threading模組msg = "is thread using threading module"th = threading.Thread(target=thread_fun, args=(msg,))th.start()#進程池方式msg = "is pool process"worker_count = 4pool = Pool(worker_count)for i in range(worker_count):pool.apply_async(process_fun, args=(msg, ))pool.close()pool.join() #主進程阻塞等待所有子進程執行完畢


執行結果如下:




著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

python 多進程與多線程淺析

相關文章

聯繫我們

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