python 多线程和多进程

官方文档: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

相关文章
相关标签/搜索