標籤: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 多進程與多線程淺析