python 多线程和多进程

发布时间:2019-06-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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 模块。

一些简单使用技巧见介绍

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的python 多线程和多进程全部内容,希望文章能够帮你解决python 多线程和多进程所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。