中国化工网,暂告安全中文字幕,邱际亨
因为 gil (global interpreter lock,全局解释器锁) 的关系,python中的多线程其实并不是真正的多线程,想要充分地使用多核cpu的资源,在python中大部分情况需要使用多进程。
使用多进程时,应注意以下几点:
方式一
from multiprocessing import process import time def f(name): time.sleep(1) print('hello', name,time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = process(target=f, args=('alvin',)) p_list.append(p) p.start() for i in p_list: p.join() print('end') 运行结果: hello alvin sun aug 12 09:34:42 2018 hello alvin sun aug 12 09:34:42 2018 hello alvin sun aug 12 09:34:42 2018 end
方式二:
from multiprocessing import process import time class myprocess(process): def __init__(self): super(myprocess, self).__init__() def run(self): time.sleep(1) print('hello', self.name,time.ctime()) if __name__ == '__main__': p_list=[] for i in range(3): p = myprocess() p.start() p_list.append(p) for p in p_list: p.join() print('end') 运行结果: hello myprocess-1 sun aug 12 09:45:07 2018 hello myprocess-2 sun aug 12 09:45:07 2018 hello myprocess-3 sun aug 12 09:45:07 2018 end
from multiprocessing import process import os, time def info(title): print(title) print('module name: ', __name__) print('parent process: ', os.getppid()) print('process id: ', os.getpid()) def f(name): info('\033[31;1mfunction f\033[0m') print('hello', name) if __name__ == '__main__': info('\033[32;1mmain process line \033[0m') time.sleep(100) p = process(target=info, args=('bob',)) p.start() p.join() 运行结果: main process line module name: __main__ parent process: 12248 process id: 1956
参考:
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论