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() #主进程阻塞等待所有子进程执行完毕
执行结果如下:
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 23:00:14