廖雪峰Python学习笔记day9

深藏阁楼爱情的钟 2022-12-25 09:56 239阅读 0赞

学习笔记day8

  1. # python study day9
  2. # 进程和线程。实现多任务的方式
  3. # 1、多进程模式
  4. # 2、多线程模式
  5. # 3、多进程+多线程模式
  6. # multiprocessing 跨平台多进程模块。Unix/Linux/Mac环境下可以使用fork创建子进程
  7. # from multiprocessing import Process
  8. # import os
  9. # def run_proc(name): # 子程序要执行的代码
  10. # print('Parent process %s (%s)...' % (name, os.getpid))
  11. # if __name__ == '__main__':
  12. # print('Parent process %s.' % os.getpid)
  13. # p = Process(target=run_proc, args=('test',)) # 通过执行函数和参数创建子进程
  14. # print('Child process will start.')
  15. # p.start() # 开始启动
  16. # p.join() # 等待子进程执行结束
  17. # print('Child process end.') #>>>
  18. # # Parent process 928.
  19. # # Child process will start.
  20. # # Run child process test (929)...
  21. # # Process end.
  22. # from multiprocessing import Pool
  23. # import os, time, random
  24. # def long_time_task(name):
  25. # print('Run task %s (%s)...' % (name, os.getpid()))
  26. # start = time.time()
  27. # time.sleep(random.random() * 3)
  28. # end = time.time()
  29. # print('Task %s runs %0.2f seconds.' % (name, (end- start)))
  30. # if __name__ == '__main__':
  31. # print('Parent process %s.' % os.getpid())
  32. # p = Pool(4) # 使用进程池批量创建子进程
  33. # for i in range(5):
  34. # p.apply_async(long_time_task, args=(i,))
  35. # print('Waiting for all subprocesses done...')
  36. # p.close() # 需要在join之前,调用后不能再添加process
  37. # p.join() # 同步,等待所有子进程结束
  38. # print('All subprocesses done.') #>>>
  39. # Parent process 22900.
  40. # # Waiting for all subprocesses done...
  41. # # Run task 0 (19656)...
  42. # # Run task 1 (10880)...
  43. # # Run task 2 (11372)...
  44. # # Run task 3 (19780)...
  45. # # Task 2 runs 0.35 seconds.
  46. # # Run task 4 (11372)...
  47. # # Task 0 runs 0.83 seconds.
  48. # # Task 3 runs 1.03 seconds.
  49. # # Task 4 runs 1.10 seconds.
  50. # # Task 1 runs 2.25 seconds.
  51. # # All subprocesses done.
  52. # 进程间的通信通过Queue、Pipes实现
  53. # from multiprocessing import Process, Queue
  54. # import os, time, random
  55. # def write(q): # 写数据进程执行代码
  56. # print('Process to write: %s' % os.getpid())
  57. # for value in [1, 2, 3]:
  58. # print('put %s to queue...' % value)
  59. # q.put(value)
  60. # time.sleep(random.random())
  61. # def read(q):
  62. # print('process to read: %s' % os.getpid())
  63. # while True:
  64. # value = q.get(True)
  65. # print('get %s from queue.' % value)
  66. # if __name__ == '__main__':
  67. # q = Queue() # 父进程创建Queue, 并传给各个子进程
  68. # pw = Process(target=write, args=(q,))
  69. # pr = Process(target=read, args=(q,))
  70. # pw.start() # 启动子进程pw, 写入
  71. # pr.start() # 启动pr, 读取
  72. # pw.join()
  73. # pr.terminate() # pr进程死循环,强行终止 >>>
  74. # # Process to write: 9468
  75. # # put 1 to queue...
  76. # # process to read: 18696
  77. # # get 1 from queue.
  78. # # put 2 to queue...
  79. # # get 2 from queue.
  80. # # put 3 to queue...
  81. # # get 3 from queue.
  82. # 多线程,python提供低级的_thread和高级的threading模块,常用threading
  83. # import time,threading
  84. # def son_thread_task():
  85. # for i in range(5):
  86. # print(threading.current_thread().name, i)
  87. # time.sleep(1)
  88. # print(threading.current_thread().name, 'running')
  89. # son_thread = threading.Thread(target=son_thread_task, name='sonthread')
  90. # son_thread.start()
  91. # son_thread.join()
  92. # print(threading.current_thread().name, 'end') #>>>
  93. # # MainThread running
  94. # # sonthread 0
  95. # # sonthread 1
  96. # # sonthread 2
  97. # # sonthread 3
  98. # # sonthread 4
  99. # # MainThread end
  100. # Lock 线程安全
  101. # import time, threading
  102. # balance = 0 # 全局银行存款变量
  103. # lock = threading.Lock()
  104. # def balance_saveAndGet(money):
  105. # global balance
  106. # balance = balance + money
  107. # balance = balance - money
  108. # def run_thread(money):
  109. # for i in range(2000000):
  110. # lock.acquire() # 获取锁后再修改
  111. # try:
  112. # balance_saveAndGet(money)
  113. # finally:
  114. # lock.release() # 释放锁。with threading.Lock() as lock:……
  115. # def main():
  116. # t1 = threading.Thread(target=run_thread,args=(5,))
  117. # t2 = threading.Thread(target=run_thread,args=(8,))
  118. # t1.start()
  119. # t2.start()
  120. # t1.join()
  121. # t2.join()
  122. # print('balance now is:', balance)
  123. # if __name__ == '__main__':
  124. # main()'
  125. # python 因为解析器设计时有GIL全局锁导致多线程无法利用多核,不过可以考虑多进程代替
  126. # ThreadLocal 全局线程变量,每个线程只能读写自己线程,互不干扰。
  127. # 解决了线程内多函数之间相互传递参数的问题。
  128. # import threading
  129. # local_school = threading.local() # 创建全局ThreadLocal对象, 可以看作是dict
  130. # def process_student():
  131. # std = local_school.student # 获取当前线程的student
  132. # print(std, threading.current_thread().name)
  133. # def process_thread(name):
  134. # local_school.student = name # 使用ThreadLocal绑定线程的student
  135. # process_student()
  136. # t1 = threading.Thread(target=process_thread, args=('Alice',),name='threada')
  137. # t2 = threading.Thread(target=process_thread, args=('Bob',),name='threadb')
  138. # t1.start()
  139. # t2.start()
  140. # t1.join()
  141. # t2.join() #>>>
  142. # # Alice threada
  143. # # Bob threadb
  144. # 单线程的异步编程模型称为协程
  145. # 在Thread和Process中当应优选Process
  146. # Process可以分布到多台机械上,Thread最大只能分布到多个CPU上
  147. # managers模块通过网络暴露Queue可以实现分布式进程
  148. # task_worker.py
  149. # import time, sys, queue
  150. # from multiprocessing.managers import BaseManager
  151. # # 创建类似的QueueManager:
  152. # class QueueManager(BaseManager):
  153. # pass
  154. # # 由于这个QueueManager只从网络上获取Queue,所以注册时只提供名字:
  155. # QueueManager.register('get_task_queue')
  156. # QueueManager.register('get_result_queue')
  157. # # 连接到服务器,也就是运行task_master.py的机器:
  158. # server_addr = '127.0.0.1'
  159. # print('Connect to server %s...' % server_addr)
  160. # # 端口和验证码注意保持与task_master.py设置的完全一致:
  161. # m = QueueManager(address=(server_addr, 5000), authkey=b'abc') #authkey连接标识
  162. # # 从网络连接:
  163. # m.connect()
  164. # # 获取Queue的对象:
  165. # task = m.get_task_queue()
  166. # result = m.get_result_queue()
  167. # # 从task队列取任务,并把结果写入result队列:
  168. # for i in range(10):
  169. # try:
  170. # n = task.get(timeout=1)
  171. # print('run task %d * %d...' % (n, n))
  172. # r = '%d * %d = %d' % (n, n, n*n)
  173. # time.sleep(1)
  174. # result.put(r)
  175. # except Queue.Empty:
  176. # print('task queue is empty.')
  177. # # 处理结束:
  178. # print('worker exit.')

在这里插入图片描述
学习笔记day10

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读