官方文檔:multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads。python
總的來講是對補救Python多線程在多核操做系統中的一副良藥。更多的推薦你們使用multiprocessing 模塊。web
一些簡單使用技巧見介紹windows
http://blog.csdn.net/dutsoft/...安全
廖雪峯python教程之多進程
其中最大的區別在於 多線程和多進程最大的不一樣在於,多進程中,同一個變量,各自有一份拷貝存在於每一個進程中,互不影響,而多線程中,全部變量都由全部線程共享服務器
運行環境 Python2.7 ,windows多線程
import time, threading # 假定這是你的銀行存款: balance = 0 def change_it(n): # 先存後取,結果應該爲0: global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(100000): change_it(n) t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance)
運行的結果會是一個隨機數,就是由於Python的多線程是不安全的,線程之間的調度會影響到其餘線程的結果。ide
#coding=utf-8 import time, threading lock = threading.Lock() # 假定這是你的銀行存款: balance = 0 def change_it(n): # 先存後取,結果應該爲0: global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(100000): lock.acquire() try: change_it(n) finally: lock.release() t1 = threading.Thread(target=run_thread, args=(5,)) t2 = threading.Thread(target=run_thread, args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance)
運行的結果是預想的0ui
另外再web服務器中會大量使用多進程的方式,gunicorn,uwsgi等spa