Python之路_Day11

Python之路_Day11_课堂笔记


前期回顾





本节摘要
一、多线程
基本使用
生产者消费者模型(队列)
自定义线程池
二、多进程
基本使用
进程池
三、协程
greenlet
gevent
四、缓存
memcache
redis
五、rabbitMQ

六、下节预告:
MySQL
ORM框架-sqlchemy
堡垒机



一、线程
创建线程的两种基本使用方法:
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import threading
  5. # def f1(arg):
  6. # print(arg)
  7. #
  8. # t = threading.Thread(target=f1,args=(123,))
  9. # t.start()
  10. class MyThread(threading.Thread):
  11. def __init__(self,func,args):
  12. self.func = func
  13. self.args = args
  14. super(MyThread,self).__init__()
  15. def run(self):
  16. self.func(self.args)
  17. def f2(arg):
  18. print(arg)
  19. obj = MyThread(f2,123)
  20. obj.start()

先进先出队列Queue:
put放数据,是否阻塞,阻塞时的超时时间
get取数据(默认阻塞),是否阻塞,阻塞时的超时时间
队列最大长度
qsize()真实个数
maxsize最大支持的个数
join,task_done,阻塞进程,当队列中任务执行完毕后,释放阻塞,不再阻塞
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import queue
  5. q = queue.Queue(3)
  6. print(q.empty())
  7. q.put(11)
  8. q.put(22)
  9. q.put(33)
  10. print(q.empty())
  11. print(q.qsize())
  12. q.put(44)
  13. q.put(55,block=False)
  14. q.put(55,block=False,timeout=2)
  15. print(q.get())
  16. print(q.get())
  17. print(q.get())
  18. print(q.get(timeout=2))
  19. q = queue.Queue(5)
  20. q.put(123)
  21. q.put(456)
  22. q.get()
  23. q.task_done()
  24. q.get()
  25. q.task_done()
  26. q.join()

后进先出队列LifoQueue:

  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import queue
  5. q = queue.LifoQueue()
  6. q.put(123)
  7. q.put(456)
  8. print(q.get())




优先级队列PriorityQueue:

  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import queue
  5. # 优先级队列
  6. q = queue.PriorityQueue()
  7. q.put((1,123))
  8. q.put((2,456))
  9. q.put((3,789))
  10. print(q.get())


双向队列deque:

  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import queue
  5. # 双向队列
  6. q = queue.deque()
  7. q.append(123)
  8. q.append(456)
  9. q.appendleft(789)
  10. q.pop()
  11. q.popleft()

生产者消费者模型:


  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. # 生产者消费者模型
  5. import queue
  6. import threading
  7. import time
  8. q = queue.Queue(20)
  9. def productor(arg):
  10. '''
  11. 买票
  12. :param arg:
  13. :return:
  14. '''
  15. q.put(str(arg) + ' 火车票 ')
  16. for i in range(300):
  17. t = threading.Thread(target=productor,args=(i,))
  18. t.start()
  19. def consumer(arg):
  20. '''
  21. 服务器后台
  22. :param arg:
  23. :return:
  24. '''
  25. while True:
  26. print(arg,q.get())
  27. time.sleep(2)
  28. for j in range(3):
  29. t = threading.Thread(target=consumer,args=(j,))
  30. t.start()


线程锁
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import threading
  5. import time
  6. NUM = 10
  7. def func(l):
  8. global NUM
  9. # 上锁
  10. l.acquire()
  11. NUM -= 1
  12. time.sleep(2)
  13. print(NUM)
  14. # 开锁
  15. l.release()
  16. lock = threading.RLock() # 支持多层所,嵌套锁
  17. # lock = threading.Lock() # 只支持单层所
  18. for i in range(10):
  19. t = threading.Thread(target=func , args=(lock,))
  20. t.start()

  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import threading
  5. def func(i,e):
  6. print(i)
  7. e.wait() # 检测时什么灯,如果是红灯,停,绿灯,行;
  8. print(i+100)
  9. event = threading.Event()
  10. for i in range(10):
  11. t = threading.Thread(target=func,args=(i,event,))
  12. t.start()
  13. event.clear() # 设置成红灯
  14. inp = input('>>>')
  15. if inp == '1':
  16. event.set() # 设置成绿灯

MF8SE9UCMHW%9HHA{YT}328.png

6H2`WT%X2ZK$[5]UHM$EU`C.png

线程池
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. import queue
  5. import threading
  6. import time
  7. class ThreadPool:
  8. def __init__(self,maxsize=5):
  9. self.maxsize = maxsize
  10. self._q = queue.Queue(maxsize)
  11. for i in range(maxsize):
  12. self._q.put(threading.Thread)
  13. def get_thread(self):
  14. return self._q.get()
  15. def add_thread(self):
  16. self._q.put(threading.Thread)
  17. pool = ThreadPool(5)
  18. def task(arg, p):
  19. print(arg)
  20. time.sleep(1)
  21. p.add_thread()
  22. for i in range(100):
  23. t = pool.get_thread()
  24. obj = t(target=task,args=(i,pool,))
  25. obj.start()





二、进程
基本使用
默认数据不共享
queues
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. # 进程基本使用,
  5. from multiprocessing import Process
  6. from multiprocessing import queues
  7. import multiprocessing
  8. def foo(i,arg):
  9. arg.put(i)
  10. print('say hi',i ,arg.qsize())
  11. if __name__ == "__main__":
  12. li = queues.Queue(20,ctx=multiprocessing)
  13. for i in range(10):
  14. p = Process(target=foo,args=(i,li,))
  15. p.start()

array
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. # 进程基本使用2
  5. from multiprocessing import Process
  6. from multiprocessing import queues
  7. import multiprocessing
  8. from multiprocessing import Array
  9. def foo(i,arg):
  10. arg[i] = i + 100
  11. for item in arg:
  12. print(item)
  13. print('============')
  14. if __name__ == "__main__":
  15. li = Array('i',10)
  16. for i in range(10):
  17. p = Process(target=foo,args=(i,li,))
  18. p.start()

Manager.dict
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. # 进程基本使用3
  5. from multiprocessing import Process
  6. from multiprocessing import queues
  7. import multiprocessing
  8. from multiprocessing import Manager
  9. def foo(i,arg):
  10. arg[i] = i + 100
  11. print(arg.values())
  12. if __name__ == "__main__":
  13. obj = Manager()
  14. li = obj.dict()
  15. for i in range(10):
  16. p = Process(target=foo,args=(i,li,))
  17. p.start()
  18. import time
  19. time.sleep(1)

进程池
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. # 进程池
  5. from multiprocessing import Pool
  6. import time
  7. def f1(arg):
  8. time.sleep(1)
  9. print(arg)
  10. if __name__ == "__main__":
  11. pool = Pool(5)
  12. for i in range(30):
  13. # pool.apply(func=f1,args=(i,))
  14. pool.apply_async(func=f1,args=(i,))
  15. # pool.close() # 所有的任务执行完毕
  16. # time.sleep(1)
  17. # pool.terminate() # 立即终止
  18. # pool.join()




PS:
IO密集型使用多线程
计算密集型使用多进程



三、协程
原理:利用一个线程,分解一个线程成为多个“微线程” ===>程序级别

greenlet
gevent
  1. #!/usr/bin/env python
  2. # -.- coding: utf-8 -.-
  3. # By sandler
  4. from gevent import monkey ; monkey.patch_all()
  5. import gevent
  6. import requests
  7. def f(url):
  8. print('GET: %s ' % url)
  9. resp = requests.get(url)
  10. data = resp.text
  11. print('%d bytes received from %s.' % (len(data),url ))
  12. gevent.joinall([
  13. gevent.spawn(f,'http://www.python.org'),
  14. gevent.spawn(f,'http://www.yahoo.com'),
  15. gevent.spawn(f,'http://www.github.com')
  16. ])



四、缓存
1、安装软件
2、程序:安装其对应的模块
Socket连接,

Memcache
1、天生的集群
2、基本操作
3、gets和cas

Redis
LQ01`K[5EZNCSLDPN7$GTJ6.png

AKYO@1Z@KI]BF@O{NE$2L)P.png












http://www.cnblogs.com/wupeiqi/articles/5132791.html


http://www.cnblogs.com/wupeiqi/articles/4839959.html


http://www.cnblogs.com/wupeiqi/articles/5040827.html












原文地址:https://www.cnblogs.com/sandler613/p/5720003.html