python多線程是偽多線程,同時間最多只有一個線程在執行,但這樣并不代碼python的多線程沒有作用,對于IO密集型的系統,python的多線程還是能極大的提升性能~
關于python偽多線程可以去了解python GIL的概念。
以下代碼涉及python多線程,多進程,進程池相關操作:
#encoding:utf-8
from multiprocessing import Pool,Manager,cpu_count,Lock,Process
import thread
import threading
def process_fun(msg):
print 'process_fun msg:', msg
pass
def thread_fun(msg):
print 'thread_fun msg:', msg
pass
if __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 = 4
pool = Pool(worker_count)
for i in range(worker_count):
pool.apply_async(process_fun, args=(msg, ))
pool.close()
pool.join() #主進程阻塞等待所有子進程執行完畢
執行結果如下:
版權聲明:本文為博主原創文章,未經博主允許不得轉載。