python 彻底解读多线程与多进程_python 多进程与多线程浅析
python多線程是偽多線程,同時(shí)間最多只有一個(gè)線程在執(zhí)行,但這樣并不代碼python的多線程沒有作用,對(duì)于IO密集型的系統(tǒng),python的多線程還是能極大的提升性能~
關(guān)于python偽多線程可以去了解python GIL的概念。
以下代碼涉及python多線程,多進(jìn)程,進(jìn)程池相關(guān)操作:
#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';
#啟動(dòng)一個(gè)子進(jìn)程
msg = "is process"
child_proc = Process(target=process_fun, args=(msg,))
child_proc.start()
#啟動(dòng)一個(gè)線程 使用thread模塊
msg = "is thread using thread module"
thread.start_new_thread(thread_fun, (msg,))
#啟動(dòng)一個(gè)線程 使用threading模塊
msg = "is thread using threading module"
th = threading.Thread(target=thread_fun, args=(msg,))
th.start()
#進(jìn)程池方式
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() #主進(jìn)程阻塞等待所有子進(jìn)程執(zhí)行完畢
執(zhí)行結(jié)果如下:
版權(quán)聲明:本文為博主原創(chuàng)文章,未經(jīng)博主允許不得轉(zhuǎn)載。
總結(jié)
以上是生活随笔為你收集整理的python 彻底解读多线程与多进程_python 多进程与多线程浅析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三联发票自己留哪一联
- 下一篇: 自由职业者申请信用卡技巧 可以提交这些