现在用python开发服务器代码,因此简单对比了一下其multi-process和multi-thread的CPU利用率
对比图(top命令),结论:python(cpython)由于GIL的存在无法使用threading充分利用CPU资源,如果服务器为多核,请考虑使用multi-process提升性能
多进程( multi-process)
多线程(multi-thread)
源代码
多进程( multi-process)
import multiprocessing
def thread_func():
print "thread in"
while True:
pass
if __name__ == "__main__":
t1 = multiprocessing.Process(target = thread_func)
t1.start()
t2 = multiprocessing.Process(target = thread_func)
t2.start()
t1.join()
t2.join()
多线程(multi-thread)
from threading import Thread
def thread_func():
print "thread in"
while True:
pass
if __name__ == "__main__":
t1 = Thread(target = thread_func)
t1.start()
t2 = Thread(target = thread_func)
t2.start()
t1.join()
t2.join()