· IO操作不占CPU,计算占用CPU
· python多线程不适合CPU密集型(1+1)操作的任务,适合IO(socketserver)密集型的任务。
代码范例1:简单的进程实现
import threading,multiprocessing, time def test(): print(threading.get_ident()) def fun(name): time.sleep(1) print("hello,",name) t = threading.Thread(target=test) t.start() if __name__ == '__main__': p = multiprocessing.Process(target=fun,args=('fone',)) p.start() p.join()
# 注意:进程使用与线程类似,但实例化之前一定要加上if __name__ == '__main__':
代码范例2:
from multiprocessing import Process import os def info(title): print(title) print('module name:', __name__) print('parent process:', os.getppid()) print('process id:', os.getpid()) print("\n") def f(name): info('\033[31;1mfrom child process function f\033[0m') print('hello', name) if __name__ == '__main__': info('\033[32;1mmain process line\033[0m') p = Process(target=f, args=('bob',)) p.start()
# 输出:
main process line
module name: __main__
parent process: 6660
process id: 7772
from child process function f
module name: __mp_main__
parent process: 7772
process id: 7648
hello bob
posted on
浙公网安备 33010602011771号