多进程实现TCP服务端并发

服务端:
import socket
from multiprocessing import Process def get_server():
server = socket.socket()
server.bind(('127.0.0.1',8088))
server.listen(5)
return server def get_talk(sock):
while True:
data = sock.recv(1024)
print(data.decode('utf8'))
sock.send(data.upper()) if __name__ == '__main__':
server = get_server()
while True:
sock, addr = server.accept()
# 开设多进程 去聊天
p = Process(target=get_talk, args=(sock,))
p.start()
客户端:
import socket client = socket.socket()
client.connect(('127.0.0.1',8088)) while True:
client.send(b'hello baby')
data = client.recv(1024)
print(data)

互斥锁代码实操

锁:建议只加载操作数据的部分 否则整个程序的效率会极低
from multiprocessing import Process,Lock
import time
import json
import random def search(name):
with open(r'data.json','r',encoding='utf8')as f:
data = json.load(f)
print('%s查看票 目前剩余:%s' % (name, data.get('ticket_num'))) def buy(name):
# 先查询票数
with open(r'data.json','r',encoding='utf8')as f:
data = json.load(f)
# 模拟网络延迟
time.sleep(random.randint(1,3))
# 买票
if data.get('ticket_num') > 0:
with open(r'data.json', 'w',encoding='utf8')as f:
data['ticket_num'] -= 1
json.dump(data,f)
print('%s 买票成功' % name)
else:
print('%s 买票失败 非常可乐 没车回去了'% name)
def run(name,mutex):
search(name)
mutex.acquire() # 抢锁
buy(name)
mutex.release() # 释放锁 if __name__ == '__main__':
mutex = Lock() # 产生一把锁
for i in range(10):
p = Process(target=run, args=('用户%s号' % i,mutex))
p.start() """
锁有很多种 但是作用都一样
行锁 表锁。。。。
"""

线程理论

进程
进程其实是资源单位 表示一块内存空间
线程
线程才是执行单位 表示真正的代码指令
我们可以将进程比喻是车间 线程是车间里面的流水线
一个进程内部至少含有一个线程 1.一个进程内可以开设多个线程
2.同一个进程下的多个线程数据是共享的
3.创建进程与线程的区别
创建进程的消耗要远远大于线程

创建线程的两种方式

from threading import Thread
from multiprocessing import Process
import time # def task(name):
# print(f'{name}is running')
# time.sleep(0.1)
# print(f'{name}is over')
#
# if __name__ == '__main__':
# start_time = time.time()
# p_list = []
# for i in range(100):
# p = Process(target=task,args=('用户%s'%i,))
# p.start()
# p_list.append(p)
# for p in p_list:
# p.join()
# print(time.time() - start_time)
# t_list = []
# for i in range(100):
# p = Process(target=task, args=('用户%s' % i,))
# p.start()
# t_list.append(p)
# for p in t_list:
# p.join()
# print(time.time() - start_time)
#
# t = Thread(target=task, args=('json',))
# t.start()
# print('主线程') """
创建线程无需考虑反复执行的问题
"""
class MyThread(Thread):
def run(self):
print('run is running')
time.sleep(1)
print('run is over') obj = MyThread()
obj.start()
print('主线程')

线程的诸多特性

1.join方法
2.同进程内多个线程数据共享
3.current_thread()
4.active_count()

GIL全局解释器锁

# 官方文档对GIL的解释
In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.
"""
1.在CPython解释器中存在全局解释器锁简称GIL
python解释器有很多类型
CPython JPython PyPython(常用的是CPython解释器)
2.GIL本质也是一把互斥锁 用来阻止同一个进程内多个线程同时执行(重要)
3.GIL的存在是因为CPython解释器中内存管理不是线程安全的(垃圾回收机制)
垃圾回收机制
引用计数 标记清除 分代回收
"""

验证GIL的存在

from threading import Thread

num = 100

def task():
global num
num -= 1 t_list = []
for i in range(100):
t = Thread(target=task)
t.start()
t_list.append(t)
for t in t_list:
t.join()
print(num)

GIL与普通互斥锁

既然CPython解释器中有GIL 那么我们以后写代码是不是就不需要操作锁了!!!!
"""
GIL只能够确保同进程内多线程数据不会被垃圾回收机制弄乱 并不能确保程序里面的数据是否安全
"""
import time
from threading import Thread,Lock num = 100 def task(mutex):
global num
mutex.acquire()
count = num
time.sleep(0.1)
num = count - 1
mutex.release() mutex = Lock()
t_list = []
for i in range(100):
t = Thread(target=task,args=(mutex,))
t.start()
t_list.append(t)
for t in t_list:
t.join()
print(num)

python多线程是否有用

需要分情况
情况1
单个CPU
多个CPU
情况2
IO密集型(代码有IO操作)
计算密集型(代码没有IO)
1.单个CPU
IO 密集型
多进程
申请额外的空间 消耗更多的资源
多线程
消耗资源相对较少 通过多道技术
ps:多线程有优势!!!
计算密集型
多进程
申请额外的空间 消耗更多的资源(总耗时+申请空间+拷贝代码+切换)
多线程
消耗资源相对较少 通过多道技术(总耗时+切换)
ps:多线程有优势!!!
2.多个CPU
IO密集型
多进程
总耗时(单个进程的耗时+IO+申请空间+拷贝代码)
多线程
总耗时(单个进程的耗时+IO)
ps:多线程有优势!!!!
计算密集型
多进程
总耗时(单个进程的耗时)
多线程
总耗时(多个进程的综合)
ps:多进程完胜!!!!!
from threading import Thread
from multiprocessing import Process
import os
import time def work():
# 计算密集型
res = 1
for i in range(1, 100000):
res *= i if __name__ == '__main__':
# print(os.cpu_count()) # 12 查看当前计算机CPU个数
start_time = time.time()
# p_list = []
# for i in range(12): # 一次性创建12个进程
# p = Process(target=work)
# p.start()
# p_list.append(p)
# for p in p_list: # 确保所有的进程全部运行完毕
# p.join()
t_list = []
for i in range(12):
t = Thread(target=work)
t.start()
t_list.append(t)
for t in t_list:
t.join()
print('总耗时:%s' % (time.time() - start_time)) # 获取总的耗时 """
计算密集型
多进程:5.665567398071289
多线程:30.233906745910645
""" def work():
time.sleep(2) # 模拟纯IO操作 if __name__ == '__main__':
start_time = time.time()
# t_list = []
# for i in range(100):
# t = Thread(target=work)
# t.start()
# for t in t_list:
# t.join()
p_list = []
for i in range(100):
p = Process(target=work)
p.start()
for p in p_list:
p.join()
print('总耗时:%s' % (time.time() - start_time)) """
IO密集型
多线程:0.0149583816528320
多进程:0.6402878761291504
"""

死锁现象

from threading import Thread,Lock
import time mutexA = Lock() # 产生一把锁
mutexB = Lock() # 产生另一把锁 class MyThread(Thread):
def run(self):
self.func1()
self.func2() def func1(self):
mutexA.acquire()
print(f'{self.name}抢到了A锁')
mutexB.acquire()
print(f'{self.name}抢到了B锁')
mutexB.release()
print(f'{self.name}释放了B锁')
mutexA.release()
print(f'{self.name}释放了A锁') def func2(self):
mutexB.acquire()
print(f'{self.name}抢到了B锁')
time.sleep(1) # 这个阻塞时间位置放到开始时不会出现
mutexA.acquire()
print(f'{self.name}抢到了A锁')
mutexA.release()
print(f'{self.name}释放了A锁')
mutexB.release()
print(f'{self.name}释放了B锁') for i in range(10):
obj = MyThread()
obj.start()
"""
死锁现象也是一个常见的现象 很典型 主要为了不要随便写锁 保证代码稳定没有问题再用
"""

信号量

在python中并发编程中信号量相当于多把互斥锁(公共厕所)

from threading import Thread,Lock,Semaphore
import time
import random sp = Semaphore(5) # 一次性产生五把锁 class MyThread(Thread):
def run(self):
sp.acquire()
print(self.name)
time.sleep(random.randint(1,3))
sp.release() for i in range(20):
t = MyThread()
t.start()

event事件

from threading import Thread, Event
import time event = Event() # 类似于造了一个红绿灯 def light():
print('红灯亮着的 所有人都不能动')
time.sleep(3)
print('绿灯亮了 油门踩到底 冲冲冲!!!!!!')
event.set() def car(name):
print('%s 正在等红灯' % name)
event.wait()
print('%s加油门 飙车了' % name) t = Thread(target=light)
t.start()
for i in range(20):
t = Thread(target=car, args=('熊猫PRO%s' % i,))
t.start()

进程池与线程池

进程和线程能否无限制的创建   不可以
因为硬件的发展赶不上软件 有物理极限 如果我们在编写代码的过程中无限制的创建进程或者线程可能会导致计算机崩溃 池
降低程序的执行效率 但是保证了计算机硬件的安全
进程池
提前创建好固定数量的进程,供后续程序的调用 超出则等待
线程池
提前创建好固定数量的线程供后续程序的调用 超出则等待
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
import os
import time
import random
from threading import current_thread # 1.产生含有固定数量线程的线程池
# pool = ThreadPoolExecutor(5)
pool = ProcessPoolExecutor(5) def task(n):
print('task is running')
time.sleep(random.randint(1,3))
print('tsk is over', n, current_thread().name)
print('task is over', os.getpid())
return '我是task函数的返回值' def func(*args, **kwargs):
print('from func') if __name__ == '__main__':
# 2.将认为提交给线程池即可
for i in range(20):
res = pool.submit(task,123) # 朝线程池提交任务
print(res.result()) # 不能直接获取
pool.submit(task,123).add_done_callback(func)

协程

"""
进程:资源单位
线程:执行单位
协程:单线程下实现并发(效率高)
在代码层面欺骗CPU 让CPU觉得代码里面没有IO操作
实际上IO操作被我们自己写的代码检测 一旦有 立刻让代码执行别的
(该技术完全是程序员自己弄出来的 名字也是程序员自己起的)
核心:自己写代码完成切换+保存状态
"""
import time
from gevent import monkey; monkey.patch_all() # 固定编写 用于检测所有的IO操作(猴子补丁)
from gevent import spawn # 第三方模块直接下载,这个模块还需要一个高版本的pycharm才可以下载使用 def func1():
print('func1 running')
time.sleep(3)
print('func1 over') def func2():
print('func2 running')
time.sleep(5)
print('func2 over') if __name__ == '__main__':
stat_time = time.time()
func1()
func2()
s1 = spawn(func1) # 检测代码 一旦有IO自动切换(执行没有IO的操作 变向的等待IO结束)
s2 = spawn(func2)
s1.join()
s2.join()
print(time.time() - stat_time) # 8.0123434543 协程 5.015565753

协程实现并发

import socket
from gevent import monkey;monkey.patch_all() # 固定编写 用于检测所有的IO操作(猴子补丁)
from gevent import spawn def communication(sock):
while True:
data = sock.recv(1024)
print(data.decode('utf8'))
sock.send(data.upper()) def get_server():
server = socket.socket()
server.bind(('127.0.0.1', 8080))
server.listen(5)
while True:
sock, addr = server.accept() # IO操作
spawn(communication, sock) s1 = spawn(get_server)
s1.join() 如何不断的提升程序的运行效率
多进程下开多线程 多线程下开协程

python之路32 网络并发线程方法 线程池 协程的更多相关文章

  1. Python菜鸟之路:Python基础-线程、进程、协程

    上节内容,简单的介绍了线程和进程,并且介绍了Python中的GIL机制.本节详细介绍线程.进程以及协程的概念及实现. 线程 基本使用 方法1: 创建一个threading.Thread对象,在它的初始 ...

  2. Python之路【第七篇】:线程、进程和协程

    Python之路[第七篇]:线程.进程和协程   Python线程 Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元. 1 2 3 4 5 6 7 8 9 10 11 12 1 ...

  3. python并发编程之Queue线程、进程、协程通信(五)

    单线程.多线程之间.进程之间.协程之间很多时候需要协同完成工作,这个时候它们需要进行通讯.或者说为了解耦,普遍采用Queue,生产消费模式. 系列文章 python并发编程之threading线程(一 ...

  4. Python之路,Day9 - 线程、进程、协程和IO多路复用

    参考博客: 线程.进程.协程: http://www.cnblogs.com/wupeiqi/articles/5040827.html http://www.cnblogs.com/alex3714 ...

  5. Python之线程、进程和协程

    python之线程.进程和协程 目录: 引言 一.线程 1.1 普通的多线程 1.2 自定义线程类 1.3 线程锁 1.3.1 未使用锁 1.3.2 普通锁Lock和RLock 1.3.3 信号量(S ...

  6. Python开发【第九章】:线程、进程和协程

    一.线程 线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务 1.t ...

  7. py 并发编程(线程、进程、协程)

    一.操作系统 操作系统是一个用来协调.管理和控制计算机硬件和软件资源的系统程序,它位于硬件和应用程序之间. 程序是运行在系统上的具有某种功能的软件,比如说浏览器,音乐播放器等.操作系统的内核的定义:操 ...

  8. Python 线程、进程和协程

    python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费时间,所以我们直接学习threading 就可以了. ...

  9. python运维开发(十一)----线程、进程、协程

    内容目录: 线程 基本使用 线程锁 自定义线程池 进程 基本使用 进程锁 进程数据共享 进程池 协程 线程 线程使用的两种方式,一种为我们直接调用thread模块上的方法,另一种我们自定义方式 方式一 ...

随机推荐

  1. 17.MongoDB系列之了解应用程序动态

    1. 查看当前操作 mongos> db.currentOp() { "inprog" : [ { "shard" : "study" ...

  2. 你的哪些骚操作会导致Segmentation Fault😂

    你的哪些骚操作会导致Segmentation Fault 前言 如果你是一个写过一些C程序的同学,那么很大可能你会遇到魔幻的segmentation fault,可能一时间抓耳挠腮,本篇文章主要介绍一 ...

  3. 齐博x1 小程序与公众号长期永久订阅消息的申请方法

    要给用户发送消息提醒的话,需要申请订阅消息.订阅消息分一次性订阅与长期永久性订阅.一次性订阅没有实际意义,用户订阅一次就只能发送一次.这里主要是指导大家如何申请永久长期订阅功能.对于公众号而言,大家先 ...

  4. python字典推导&&列表推导&&输出随机数

    字典推导: x = ['A', 'B', 'C', 'D'] y = ['Alice', 'Bob', 'Cecil', 'David'] print({i:j for i,j in zip(x,y) ...

  5. css文字单行/多行超出显示省略号...

    css文字单行/多行超出显示省略号... 项目里写css样式我们经常会遇到将文字超出显示省略号的情况,记录一下以后能用到. 单行超出 .oneline { width:300upx; /*宽度一定要设 ...

  6. python模拟登录获取网站cookie

    因工作的需要需要使用某第三方网站页面的功能,但其网站未提供API,只有登录用户可使用该功能. 之前试过php使用snoopy获取set-cookie内容项进行手动拼装cookie,使用一段时间后发现网 ...

  7. 解决vue中对象属性改变视图不更新的问题

    在使用VUE的过程中,会遇到这样一种情况, vue data 中的数据更新后,视图没有自动更新. 这个情况一般分为两种, 一种是数组的值改变,在改变数组的值的是时候使用索引值去更改某一项,这样视图不会 ...

  8. 孙荣辛|大数据穿针引线进阶必看——Google经典大数据知识

    大数据技术的发展是一个非常典型的技术工程的发展过程,荣辛通过对于谷歌经典论文的盘点,希望可以帮助工程师们看到技术的探索.选择过程,以及最终历史告诉我们什么是正确的选择. 何为大数据   "大 ...

  9. win 10 玩红警/黑边,不能全屏,闪退

    win 10玩红警黑边问题 1.下载ddraw.dll,放在游戏目录 下载链接:ddraw.dll 如果提示 选择保留就行了 2.Win 键+S键,搜索注册表,打开这个 进去按这个路径    计算机\ ...

  10. java环境改完版本后无效

    把C盘program files和X86两个文件夹中的Common Files中的Oracle文件夹删掉 这是jdk安装时自动生成的两个文件夹,记录了jdk的版本和路径,即使你的jdk安装路径不在C盘 ...