1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python 彻底解读多线程与多进程_python 多进程与多线程浅析

python 彻底解读多线程与多进程_python 多进程与多线程浅析

时间:2019-04-22 12:06:37

相关推荐

python 彻底解读多线程与多进程_python 多进程与多线程浅析

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() #主进程阻塞等待所有子进程执行完毕

执行结果如下:

版权声明:本文为博主原创文章,未经博主允许。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。