python多线程和多进程详解_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多线程在多核操作系统中的一副良药。更多的推荐大家使用multiprocessing 模块。

一些简单使用技巧见介绍

廖雪峰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的多线程是不安全的,线程之间的调度会影响到其他线程的结果。

#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)

运行的结果是预想的0

另外再web服务器中会大量使用多进程的方式,gunicorn,uwsgi等

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值